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?