Reputation: 587
How to get max amount of value in same key in array
E.x
I have this array.
Array
(
[id] => 1
[amount] => 4
)
Array
(
[id] => 1
[amount] => 3
)
Array
(
[id] => 2
[amount] => 3
)
I want below result . means i want max amount value for same id .please provide solution for same.
Array
(
[id] => 1
[amount] => 4
)
Array
(
[id] => 2
[amount] => 3
)
Upvotes: 2
Views: 196
Reputation: 1146
You could use usort to sort the array by the highest amount first, then just get the first result back. For example:
usort($theBigArray, function($a, $b) {
return ($a['amount'] - $b['amount']);
});
print_r($theBigArray);
Upvotes: 1
Reputation: 5041
<?php
$bigArray = [
[
'id' => 1,
'amount' => 4
],
[
'id' => 1,
'amount' => 3
],
[
'id' => 2,
'amount' => 3
]
];
$output = [];
foreach($bigArray as $innerArray){
if(!isset($output[$innerArray['id']])){
$output[$innerArray['id']] = $innerArray;
}
elseif( $output[$innerArray['id']]['amount'] < $innerArray['amount'] ){
$output[$innerArray['id']] = $innerArray;
}
}
print_r($output);
exit;
Upvotes: 1