PDA

View Full Version : PHP Maximization function




hiddenpremise
Sep 4, 2009, 04:49 PM
Hi,
I have an array of objects. Each object has a property that is an int. I want to pick out of the array the object with the max for that particular property. Is there a smart way to do this?


class example
{
public $property;
private $otherProperty;
private $yetAnother;
}

$array[0] = new example;
$array[0]->property=10;
$array[1] = new example;
$array[1]->property=11;

(example)$maxItem = max($array->property)
//In this example it should return the item at $array[1]



angelwatt
Sep 4, 2009, 06:09 PM
Here's two ways I can think of.

// Method 1: Sort array
usort($array, "ExampleSort");
$max = $array[0];
echo $max->property . "<br>"; // outputs 11

// Custom sort, max to min
function ExampleSort($a, $b)
{
if ($a->property == $b->property) { return 0; }
if ($a->property > $b-property) { return -1; }
else { return 1; }
}

// Method 2: Loop through
$max = $array[0];
for ($a=1, $b=count($array); $a<$b; ++$a) {
if ($array[$a]->property > $max->property) { $max = $array[$a]; }
}
echo $max->property . "<br>"; // outputs 11

Guiyon
Sep 4, 2009, 06:31 PM
You could also just run a reduce over the array (my PHP is a bit rusty...):

function rmax( $v, $w )
{
$vi = (is_null($v)) ? 0 : $v->property;
$wi = $w->property;

if( $vi > $wi ) {
return $v;
} else {
return $w;
}
}

$max = array_reduce( $array, "rmax", NULL );

echo $max->property . "<br/>";

Or, if you're running PHP 5.3.0 or higher:

$func = function( $v, $w )
{
$vi = (is_null($v)) ? 0 : $v->property;
$wi = $w->property;

if( $vi > $wi ) {
return $v;
} else {
return $w;
}
};

$max = array_reduce( $array, $func, NULL );

echo $max->property . "<br/>";

hiddenpremise
Sep 4, 2009, 10:45 PM
Your replies are greatly appreciated! I ended up using the array_reduce function as I am running 5.3.0.

Thanks,
Whit