duanqin7791 2018-04-18 10:58
浏览 21
已采纳

如何根据不会出现在所有元素中的值对php数组进行排序?

I am having a php array as follows;

$array =Array(
[310] => Array
    (
        [vendorname] => Utsav the vendor
    )
[309] => Array
    (
        [vendorname] => Ashish vendor
        [suggest_order] => 1
    )
[308] => Array
    (
        [vendorname] => praveen rathod vendor
    )
[262] => Array
    (
        [vendorname] => Yash Vendor
        [suggest_order] => 0
    )
[264] => Array
    (
        [vendorname] => amol vendro
        [suggest_order] => 2
    ));

And I want to sort it based on suggest_order key so lowest suggest_order key's value should come first and than higher value and in last their comes all remaining elements which don't even have suggest_order key like;

$array =Array(
[262] => Array
    (
        [vendorname] => Yash Vendor
        [suggest_order] => 0
    )
[309] => Array
    (
        [vendorname] => Ashish vendor
        [suggest_order] => 1
    )
[264] => Array
    (
        [vendorname] => amol vendro
        [suggest_order] => 2
    )
[310] => Array
    (
        [vendorname] => Utsav the vendor
    )

[308] => Array
    (
        [vendorname] => praveen rathod vendor
    ));

I have tried PHP Sort Array By SubArray Value .

function cmp_by_optionNumber($a, $b) {
  return $a["suggest_order"] - $b["suggest_order"];
}
print_r(usort($array, "cmp_by_optionNumber"));

And I have also tried 2nd option in above answer,

$new_array=usort($array, function ($a, $b) {
    return $a['suggest_order'] - $b['suggest_order'];
});
print_r($new_array);

But I am getting "1" in response; Any help will be appreciated.

  • 写回答

2条回答 默认 最新

  • dongzuozhu66776 2018-04-18 11:00
    关注

    All sort methods take the array to sort as reference. So you don't have to care about the return value, as the sorting is done in place.

    function cmp_by_optionNumber($a, $b) {
      return $a["suggest_order"] - $b["suggest_order"];
    }
    usort($array, "cmp_by_optionNumber");
    print_r($array);
    

    If you need to do some special handling for suggest_order, you could use isset inside the sort function.

    usort($array, function($a, $b) {
        if (isset($a["suggest_order"]) && isset($b["suggest_order"])) {
            return $a["suggest_order"] - $b["suggest_order"];
        }
        if (isset($a["suggest_order"])) {
            return -1;
        }
        if (isset($b["suggest_order"])) {
            return 1;
        }
        return 0;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并