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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog