首页 > 解决方案 > 自定义数组按输入字符串和位置排序

问题描述

我有一个数组。看起来像:

$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]
];

如何对上面的数据进行排序以使其看起来像(如果 q='motor' 在搜索字符串中):

 $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]
    ];

所以:

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

谢谢!

更新(问题/答案) ps:我正在尝试使用自定义变量作为输入:$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;
    });

并且该功能停止工作。我该如何解决这个问题?

标签: phpsortingksort

解决方案


您可以使用usort

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

如果您需要不同的订单,只需更改功能以满足您的需求。


推荐阅读