du8980919 2018-08-17 20:49
浏览 41
已采纳

自定义数组按输入字符串和位置排序

I have an array. It' looks like:

$arr = [
   '0' => ['id'=>9, 'q'=>'motor', 'pos'=>1],
   '1' => ['id'=>10, 'q'=>'NULL', 'pos'=>0],
   '2' => ['id'=>7, 'q'=>'motor', 'pos'=>2],
   '3' => ['id'=>8, 'q'=>'NULL',  'pos'=>0],
   '4' => ['id'=>11, 'q'=>'motor','pos'=>3],
   '5' => ['id'=>11, 'q'=>'exhaust','pos'=>1]
];

How can I sort the data above to make it looks like (if q='motor' is inside search string):

 $arr = [
       '0' => ['id'=>9, 'q'=>'motor', 'pos'=>1],
       '2' => ['id'=>7, 'q'=>'motor', 'pos'=>2],
       '4' => ['id'=>11, 'q'=>'motor','pos'=>3],
       '1' => ['id'=>10, 'q'=>'NULL', 'pos'=>0],
       '3' => ['id'=>8, 'q'=>'NULL',  'pos'=>0],
       '5' => ['id'=>11, 'q'=>'exhaust','pos'=>1]
    ];

So:

function custom_sort($input_query, $arr) {
   foreach($arr as $key=>$row) {
      if (strpos($input_query, $row['q'])) {
          ... How to Sort By Pos?
      }
   }
}

Thanks!

Updated (question/answer) p.s: I'm trying to use custom variable as input: $q

usort($arr, function($a, $b) use ($q) {
        if ($a['q'] == $q) {
            if($b['q'] == $q) {
                return ($a['pos'] > $b['pos']) ? 1 : -1;
            }
            return -1;
        }
        if ($b['q'] == $q) {
            return 1;
        }
        return 0;
    });

And the function stop working. How can I solve this?

  • 写回答

3条回答 默认 最新

  • douge3113 2018-08-17 21:11
    关注

    Here's a usort that handles your requirements, wrapped in a function that transforms the array in place:

    1. Items with q key containing $query will be placed at the front of the array.

    2. Items with q key containing $query will be sorted ascending by their pos value.

    3. Everything else will be sorted by its pos value.

    function custom_sort($query, &$arr) {
        usort($arr, function($a, $b) use ($query) {
            $in_a = strpos($a['q'], $query) !== false;
            $in_b = strpos($b['q'], $query) !== false;
    
            if ($in_a && !$in_b) {
                return -1;
            }
            if (!$in_a && $in_b) {
                return 1;
            }
    
            return $a['pos'] - $b['pos'];
        });
    }
    
    custom_sort("motor", $arr);
    

    Test it on a large dataset in this repl.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站