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'];
});
Hamid Ali
8851 gold badge8 silver badges22 bronze badges
1 Answer 1
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
)
answered Jun 29, 2020 at 10:15
-
thanks its works can you tell me the menaing of this PHP_INT_MIN?user– user2020年06月29日 10:20:22 +00:00Commented Jun 29, 2020 at 10:20
-
PHP_INT_MIN
is just the lowest integer value, this should ensure that any value compared against it will be greater than it is.Nigel Ren– Nigel Ren2020年06月29日 10:21:19 +00:00Commented Jun 29, 2020 at 10:21
lang-php
$categories
array come from a database?WHERE category_id IN (239,240,238)
. No need to loop any array.