vishal_g
vishal_g

Reputation: 3921

find max value in associative array with condition

$a=2;
$b=6;
$c=7;
$r1=8;
$r2=9;
$r3=6;
$array = array(
  array('MIDDAY'=>$a,'RATE'=>$r1),
  array('SHORTDAY'=>$b,'RATE'=>$r2),
  array('LONGDAY'=>$c,'RATE'=>$r3)
);

I have a array like this and i want this array to process and want to check whose count is greater like as above LONGDAY=7 then i want this LONGDAY key in one variable and its RATE in other variable

And also want to check if two count is equal then like LONGDAY=7 and MIDDAT=7 then i want to check with RATE whose rate is greater then same i want this LONGDAY key in one variable and its RATE in other variable (for RATE is greater in this case)

Upvotes: 0

Views: 550

Answers (1)

deceze
deceze

Reputation: 522005

Something along these lines should do it to sort the array according to your rules and take the top result.

$array = array(
  array('type' => 'MIDDAY',   'val' => $a, 'rate' => $r1),
  array('type' => 'SHORTDAY', 'val' => $b, 'rate' => $r2),
  array('type' => 'LONGDAY',  'val' => $c, 'rate' => $r3)
);

usort($array, function ($a, $b) {
    if      ($a['val'] < $b['val']) return 1;
    else if ($a['val'] > $b['val']) return -1;
    else    return $b['rate'] - $a['rate'];
});

$var1 = $array[0]['type'];
$var2 = $array[0]['rate'];

Note, this uses PHP 5.3+ anonymous function syntax.

Upvotes: 1

Related Questions