php - 自定义数组按输入字符串和位置排序
问题描述
我有一个数组。看起来像:
$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;
});
并且该功能停止工作。我该如何解决这个问题?
解决方案
您可以使用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;
});
如果您需要不同的订单,只需更改功能以满足您的需求。
推荐阅读
- ajax - do_shortcode 没有运行 ajaxlaodmore 简码
- weblogic12c - weblogic 服务器进入警告状态
- bigdata - 有没有更好的方法来优化 python 中两个 260k 行的大列表的 compare_code,它仅适用于 fes 行
- angular - Angular mat-tab-group 和 tinyMCE
- asp.net - VS2017 - 无法发布项目(对象引用未设置为对象的实例)
- sql - 如何在 sql 列中查找代理字符?
- symfony - Symfony - 关联字段的实体类型的预期值改为“字符串”
- ios - 为什么数据没有通过我的代码中的 segue 传递?
- javascript - 使用 Google Plus 进行 Ionic Angular Firebase 身份验证不起作用
- javascript - RxJS 映射数组与另一个可观察对象并返回数组