tags:

views:

812

answers:

5

hello, does anybody know how could I get the TWO most largest values from the third column on the following array?

$ar = array(array(1, 1,   7.50,   'Hello'),
              array(1, 2,  18.90,   'Hello'),
              array(3, 5,  11.50,   'Hello'),
              array(2, 4,  15.90,  'Hello'));

Output should be:

15.90
18.90

Thanks in advance

+2  A: 

If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using usort and providing an appropriate callback. Then take the first two values:

function cmp($a, $b) {
    $a = $a[2];
    $b = $b[2];
    return $a == $b ? 0 : $a < $b ? 1 : -1;
}

usort($ar, 'cmp');
Konrad Rudolph
A: 

One of the simplest ways to do this is to collect all the values into a single array, sort the array, then print out the first two values.

There are more efficient ways that don't involve sorting the whole array, but the above should get you started.

Greg Hewgill
+2  A: 

Sorting is O(n log n), but you can actually accomplish this in O(n) (that is, faster, if the array is big). Pseudocode follows:

first  = array[0][2]
second = array[1][2]
if second > first
   first, second = second, first
for tuple in array[2:n]
   if tuple[2] > second
      second = tuple[2]
   if second > first
      first, second = second, first
Federico Ramponi
Curious how we can write Python code, omit some colon, and call it pseudocode. Isn't it?:^)
Federico Ramponi
+1  A: 

A more general solution, for the n greatest values (pseudo-code)

def maxN(list, n):
    result = []
    curmin = 0
    for number in list:
        if number > curmin:
            binary insert number into result.    #O(log n)
            if len(result) > n:  
                truncate last element            #O(1)
            curmin = new minimum in result list  #O(1) since list is sorted

    return result

The whole thing will take... O(m log n), where m is the size of the list and n is the number of max elements you want. This is much better than if you sort the list, which takes O(n log n), for large n.

But it's also overkill if you just want the max two elements.

Claudiu
A: 

Where are you getting the array data from? How often will the data change? Can you get the array already sorted by that field? If there are a large number of data items, might it be worth doing a second query?

Hugh Bothwell