0

I have an array in this format:

 Array
(
    [0] => Array
        (
            [id] => 117
            [name] => Apple
            [amount] => 300
        )

    [1] => Array
        (
            [id] => 188
            [name] => Orange
            [count] => 20
        )

    [2] => Array
        (
            [id] => 189
            [name] => Grapes
            [amount] => 7000
        )

)

I'm trying to get the id of max amount from the associative array. how can i perform this?

i'm expecting the result

Array
    (
        [2] => Array
            (
                [id] => 189
                [name] => Grapes
                [amount] => 7000
            )
    
    )
mathew
  • 86
  • 7

1 Answers1

2

It's simplest to just initialise a "maxkey" value with 0 and then iterate over the array, replacing the key when you find a value with a higher amount:

$maxkey = 0;
foreach ($data as $key => $value) {
    if ($value['amount'] > $data[$maxkey]['amount']) {
        $maxkey = $key;
    }
}
print_r($maxkey);
print_r($data[$maxkey]);

Output:

2
Array
(
    [id] => 189
    [name] => Grapes
    [amount] => 7000
)
Nick
  • 138,499
  • 22
  • 57
  • 95