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

Posted by DavidYell on Stack Overflow See other posts from Stack Overflow or by DavidYell
Published on 2010-03-15T10:43:40Z Indexed on 2010/03/15 10:59 UTC
Read the original article Hit count: 160

Filed under:
|

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 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?

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays