dongxiaowei_1234 2015-07-28 16:49 采纳率: 0%
浏览 25
已采纳

手动排序类别PHP usort

I have four categories with category IDs 4,6,7,10 that I would like to sort in the following order 4,7,6,10.

I was using usort to do this, and it worked fine before I added category 10. Now I'm adding 10 and the order I get is 10,4,7,6.

A var_dump($categories); before the usort gives the following output:

array(4) {
[0]=>
string(1) "6"
[1]=>
string(1) "4"
[2]=>
string(1) "7"
[3]=>
string(2) "10"
}

I define the order I want the categories in an array, and use that in the usort:

$order = array(4,7,6,10);
            usort($categories, function ($a, $b) use ($order) {
                $pos_a = array_search($a['string'], $order);
                $pos_b = array_search($b['string'], $order);
                return $pos_a - $pos_b;
            });

A var_dump($categories); after the usort gives:

array(4) {
  [0]=>
  string(2) "10"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "7"
  [3]=>
  string(1) "6"
}

I can't figure out why category 10 wants to pop to the beginning of the array instead of the end. Also, I don't know if this is relevant or not but category 10 is the only one with string(2), all others have string(1).

Is the usort as I have it only capable of sorting a limited number of categories? I don't see why it would be, but that's the only thing I can come up with.

Any ideas how I could get the categories sorted in 4,7,6,10 order as it is in the array would be appreciated.

  • 写回答

1条回答 默认 最新

  • douling6469 2015-07-28 16:58
    关注

    your code was not correct. here's it corrected:

    $categories = array('6','4','7','10');

    var_dump($categories);
    $order = array(4,7,6,10);
    usort($categories, function ($a, $b) use ($order) {
        $pos_a = array_search($a, $order);
        $pos_b = array_search($b, $order);
        return $pos_a - $pos_b;
    });
    
    
    var_dump($categories);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?