Reputation: 73
I am facing one issue for getting the highest value from array. I have two arrays. First array is below:
$catids = [239,240,238]
Second array is multidimensional array below:
$categories = Array
(
[0] => Array
(
[category_id] => 239
[final_price] => 1999
)
[1] => Array
(
[category_id] => 238
[final_price] => 2990
)
[2] => Array
(
[category_id] => 240
[final_price] => 3500
)
[3] => Array
(
[category_id] => 241
[final_price] => 500
)
)
Expected Out
Array
(
[category_id] => 240
[final_price] => 3500
)
In my input array catid 240 is having heighest value 3500.
What I've tried
I have sorted the array by final_price in ascending order
usort($categories, function($a, $b) {
return $a['final_price'] <=> $b['final_price'];
});
Upvotes: 0
Views: 58
Reputation: 57121
Doing this in PHP is simple enough, you could just loop through the categories and check first that the category_id is in the array of category id's you are interested in, then compare the final_price against the current maximum...
$max = ["final_price" => PHP_INT_MIN];
foreach ( $categories as $category ) {
if ( in_array($category["category_id"], $catids)
&& $category["final_price"] > $max["final_price"] ) {
$max = $category;
}
}
print_r($max);
which with the test data gives...
Array
(
[category_id] => 240
[final_price] => 3500
)
Upvotes: 2