I am working with php, I am getting data in foreach loop and in some element there is key "profile_image_max_id" and some elements are empty
- I want to sort data according to maximum "profile_image_max_id"(if exist),So highest value of "profile_image_max_id" should be one
- in some elements(inside foreach), where "profile_image_max_id" not exit should come with any randombaly/any order
Here is my current data
Array
(
[46456] => Array
(
[id] => 46456
[status] => approved
[profile_image] => isProfile
[profile_image_max_id] =>
)
[46457] => Array
(
[id] => 46457
[status] => approved
[profile_image] => isProfile
[profile_image_max_id] =>
)
Here is my current code,Where i am wrong ?
$final = array();
foreach ( $photos as $key $photo ) :
$final[$key] = $row['price'];
endforeach;
array_multisort($final, SORT_DESC, $photos);
CodePudding user response:
You can use uasort
to do this by passing in a custom callback like below.
We return minimum value of INT if the profile_image_max_id
key is not present, making it come at last. Otherwise, the profile_image_max_id
is sorted in descending order.
<?php
uasort($data, function($a, $b){
$a_image_id = $a['profile_image_max_id'] ?? PHP_INT_MIN;
$b_image_id = $b['profile_image_max_id'] ?? PHP_INT_MIN;
return $b_image_id <=> $a_image_id;
});