簡體   English   中英

如果 php 中的某些元素中存在鍵,如何使用值對數組進行排序

[英]How to sort array with value if key exist in some elements in php

我正在使用 php,我在 foreach 循環中獲取數據,在某些元素中有鍵“profile_image_max_id”,有些元素為空

  1. 我想根據最大“profile_image_max_id”(如果存在)對數據進行排序,所以“profile_image_max_id”的最高值應該是一個
  2. 在某些元素中(在 foreach 內),其中“profile_image_max_id”不退出應該帶有任何 randombaly/any order

這是我目前的數據

    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] => 
        )

這是我當前的代碼,我哪里錯了?

$final = array();
 foreach ( $photos as $key  $photo ) : 
$final[$key] = $row['price'];
 endforeach; 
array_multisort($final, SORT_DESC, $photos);

您可以使用uasort通過傳入如下所示的自定義回調來執行此操作。 如果profile_image_max_id鍵不存在,我們將返回 INT 的最小值,使其最終出現。 否則, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM