[英]How to sort array with value if key exist in some elements in php
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我正在使用 php,我在 foreach 循环中获取数据,在某些元素中有键“profile_image_max_id”,有些元素为空
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);
You can use uasort
to do this by passing in a custom callback like below.您可以使用uasort
通过传入如下所示的自定义回调来执行此操作。 We return minimum value of INT if the profile_image_max_id
key is not present, making it come at last.如果profile_image_max_id
键不存在,我们将返回 INT 的最小值,使其最终出现。 Otherwise, the profile_image_max_id
is sorted in descending order.否则, profile_image_max_id
按降序排列。
<?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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.