开发者

Finding and marking the largest of three values in a two dimensional array

I am working on a display screen for our office, and I can't seem to think of a good way to find the largest numerical value in a set of data in a two dimensional array. I've looked at using max() and also asort() but they don't seem to cope with a two dimensional array.

I'm returning my data through our mysql class, so the rows are returned in a two dimensional array.

Array(
 [0] => Array(
  [am] => 12,
  [sales] => 981),
 [1] => Array(
  [am] => 43,
  [sales] => 1012),
 [2] => Array(
  [am] => 17,
  [sales] => 876)
)

I need to output a class when foreaching the data in my table for the AM with the highest sales value. Short of comparing them all in > if statements. I have tried to get max() on the array, but it returns an array, as it's look within the dimension. When pointing it at a specific dimension it returns the key not the value.

I figured that I开发者_如何学Go could asort() the array and pop the top value off, store it in a variable and then compare against that in my foreach() loop, but that seems to have trouble sorting across two dimensions.

Lastly, I figured that I could foreach() the values, comparing them against the previous one each time, untill I found the largest. This approach however means storing every value, luckily only three, but then comparing against them all again.

Surely there must be a simpler way to achieve this, short of converting it into a single dimension array, then doing an asort() on that?


<?php
function customSort($a, $b)
{
    if($a['sales'] == $b['sales'])
        return 0;
    else
        return $a['sales'] < $b['sales'] ? -1 : 1;
}

usort($array, 'customSort');
?>

Is what I would do

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜