简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM