0

I have an array from a MySQL query that has two parts to it, I want to get the max from just the first part, but when I do max($row) it returns the max of a date because those values are higher. When I try max(array_column($row, 'SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)')); I get this error max(): Array must contain at least one element Is there a way to do it only based on the first part?

Array
(
    [SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)] => 19.1630000055071
    [DATE] => 2013-11
)
Michael St Clair
  • 5,937
  • 10
  • 49
  • 75
  • Is this a multidimensional array, and you want the sub-array with the greatest value for `SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)`? [This answer is probably what you're after](http://stackoverflow.com/a/17339754/541091) – Michael Berkowski Jan 01 '15 at 05:41
  • 1
    If it is multidimensional, post a little more of the array for context, and clarify what your output should be -whether the entire sub-array, or just the single value like `19.1630000055071`. If you have PHP 5.5, it can be easily done with `max(array_column())` – Michael Berkowski Jan 01 '15 at 05:43
  • It is a multi dimensional array, array_column looks like the right thing so I tried this `max(array_column($row, 'SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)'));` but I get this error `max(): Array must contain at least one element` – Michael St Clair Jan 01 '15 at 06:14

1 Answers1

0

Use foreach while keeping track of the attribute you want. Take Date for example. Keep a variable MaxDate = FirstRow[Date]. Then Iterate through all of them and check if the actual row is higher than the actual MaxDate. This is a brute-force way, but it will surely work. You can also use SQL to actually take the max.

SELECT MAX(something) FROM 
       SELECT SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS something
       FROM whatever;

PHP Brute-force:

$max = $result[0]['SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)'];
foreach($result as $row){
    if($row['SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)'] > $max)
         max = $row['SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)'];
}

echo $max;

Note that you have to use all rows in the result. Remember to check whether or not there are elements in the query result.