Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get highest value in multi multidimensional array [duplicate]

i need to get the the max or highest value in a multi dimensional array.

here is my array $array:

[pay] => Array
(
    [0] => Array
        (
            [title] => Array
                (
                    [name] => 'hi'
                )
            [payment] => Array
                (
                    [amount] => 35
                    [currency] => USD
                )
        )

    [1] => Array
        (
            [title] => Array
                (
                    [name] => 'lol'
                )
            [payment] => Array
                (
                    [amount] => 50
                    [currency] => USD
                )
        )

    [2] => Array
        (
            [title] => Array
                (
                    [name] => 'ok'
                )
            [payment] => Array
                (
                    [amount] => 30
                    [currency] => USD
                )
        )
)

i need to get the max value for amount which is 50. how can i do that?

here is what i tried but it did not work:

$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;

foreach($array as $k=>$v)
{
    if($v['Total']>$max)
    {
        $max = $v['Total'];
        $found_item = $v;
    }
}
like image 886
John Jaoill Avatar asked May 17 '17 03:05

John Jaoill


2 Answers

Simple as this one-liner. Get the payment column data, then pull the amount data from that generated array, then get the max value. Done and done. (Sorry it took me so long -- I had to convert your posted array to a usable php array.)

Input:

$array=["pay" => [
            ["title"=>["name"=>'hi'],"payment"=>["amount"=>35,"currency"=>"USD"]],
            ["title"=>["name"=>'lol'],"payment"=>["amount"=>50,"currency"=>"USD"]],
            ["title"=>["name"=>'ok'],"payment"=>["amount"=>30,"currency"=>"USD"]]
    ]
];

Method #1 (Demo):

echo max(array_column(array_column($array["pay"],"payment"),"amount"));

Method #2 (Demo):

$max=0;
foreach($array["pay"] as $subarray){
    if($max<$subarray["payment"]["amount"]){
        $max=$subarray["payment"]["amount"];
    }
}
echo $max;

Method #3 (Demo):

$payments=array_column($array["pay"],"payment"); // declare payments array
rsort($payments);                                // sort by amount DESC
echo $payments[0]["amount"];                     // access the first amount value

Output:

50

The benefits to method #1 are: code brevity, no condition statements, no global variable declarations/overwriting, just straight to the max value. What's not to love!

If method #1 is too scary, you can go with my method #2 (which was first posted by aendeerei). I don't prefer it because it requires the extra steps of initializing the $max variable, performing a conditional check on each iteration, and overwriting the $max variable when appropriate. Actual performance on the foreach loop is going to depend on the size of your array, but the difference between the two methods is going to be unnoticable to humans.

Method 3 might be my new favorite because there are no conditionals and just two functions before it is accessed purely by keys. However, it does require the declaration of a partial copy of the input array which must be sorted. Anyhow, take your pick -- it's all the same outcome.

like image 172
mickmackusa Avatar answered Oct 13 '22 02:10

mickmackusa


Use Usort and get the 1st index

$arr= array
(
     array
        (
            'payment' => array
                (
                    'amount' => 35,
                    'currency' => 'USD'
                )
        ),

     array
        (
            'payment' => array
                (
                    'amount' => 50,
                    'currency' => 'USD'
                )
        ),
     array
        (
            'payment' => array
                (
                    'amount' => 80,
                    'currency' => 'USD'
                )
        )
);

function sortAmount($x, $y) {
    return $y['payment']['amount'] - $x['payment']['amount'];
}

usort($arr, 'sortAmount');
echo "<pre>";
$highest=$arr[0];
print_r($highest)
//for value only
$highest=$arr[0]['payment']['amount'];

Working fiddle http://phpfiddle.org/main/code/p5hw-ivei

like image 28
sumit Avatar answered Oct 13 '22 00:10

sumit