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条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?