简体   繁体   中英

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

  1. 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
  2. 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);

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM