У меня есть следующий массив, и я хотел бы отсортировать его на основе $ term = «geo» только в отношении [result_title]
?
Array
(
[0] => Array
(
[result_title] => Agathoklis Georgiou
[result_subtext] => Active Employee
)
[1] => Array
(
[result_title] => Frixos Georgiou
[result_subtext] => Active Employee
)
[2] => Array
(
[result_title] => George Ellinas
[result_subtext] => Active Employee
)
[3] => Array
(
[result_title] => Georgi Georgiev
[result_subtext] => Active Employee
)
[4] => Array
(
[result_title] => Charalambos Georgiou
[result_subtext] => Former Employee
)
[5] => Array
(
[result_title] => Georgia Kantouna
[result_subtext] => Former Employee
)
)
Желаемый результат должен быть:
Array
(
[0] => Array
(
[result_title] => George Ellinas
[result_subtext] => Active Employee
)
[1] => Array
(
[result_title] => Georgi Georgiev
[result_subtext] => Active Employee
)
[2] => Array
(
[result_title] => Georgia Kantouna
[result_subtext] => Former Employee
)
[3] => Array
(
[result_title] => Agathoklis Georgiou
[result_subtext] => Active Employee
)
[4] => Array
(
[result_title] => Charalambos Georgiou
[result_subtext] => Former Employee
)
[5] => Array
(
[result_title] => Frixos Georgiou
[result_subtext] => Active Employee
)
)
Я пробовал различные методы, такие как:
usort($data, function($a, $b) use ($term) {
$x = strpos($a["result_title"], $term) === false;
$y = strpos($b["result_title"], $term) === false;
if ($x && !$y) return 1;
if ($y && !$x) return -1;
// use this if you want to sort alphabetically after the keyword sort:
return strcmp($a["result_title"], $b["result_title"]);
// or if you only want to sort by whether or not the keyword was found:
return 0;
});
а также
usort($data, function ($a, $b) use ($term) {
similar_text($term, $a["result_title"], $percentA);
similar_text($term, $b["result_title"], $percentB);
return $percentA === $percentB ? 0 : ($percentA > $percentB ? -1 : 1);
});
а также
usort($data, function ($a, $b) use ($term) {
$levA = levenshtein($term, $a["result_title"]);
$levB = levenshtein($term, $b["result_title"]);
return $levA === $levB ? 0 : ($levA > $levB ? 1 : -1);
});
а также
usort($data, function($a, $b){ return $a["result_title"] - $b["result_title"]; });
и многое другое без какого-либо надлежащего результата. Или, может быть, я не могу понять метод достижения моего результата?
Я также проверил: php сортировка массива на основе строки а также Как отсортировать массив по сходству по отношению к введенному слову. но ответы дают мне результат, который я ищу.
Вот функция, которая, я думаю, будет делать то, что вы хотите. Я предположил, что вы хотите найти значение $term
в начале слова. Этот код извлекает любое ключевое слово в заголовке, который включает в себя $term
и затем сортирует на основе того, было ли найдено ключевое слово, с последующим упорядочением ключевого слова или, если они оба одинаковы, в заголовке.
$term = 'geo';
usort($data, function ($a, $b) use ($term) {
// find the term in first entry
$t1 = preg_match("/^.*?\b($term\w*)\b.*\$/i", $a['result_title'], $matches) ? $matches[1] : '';
// find the term in second entry
$t2 = preg_match("/^.*?\b($term\w*)\b.*\$/i", $b['result_title'], $matches) ? $matches[1] : '';
// check if the terms were found
if ($t1 == '' && $t2 != '') return 1;
if ($t1 != '' && $t2 == '') return -1;
// found in both - if not the same, just sort on the keyword
if ($t1 != $t2) return strcmp($t1, $t2);
// found the same keyword, sort on the whole title
return strcmp($a['result_title'], $b['result_title']);
});
Так как вывод длинный (это то, что вы просили), я опустил его, но я сделал демо на 3v4l.org.
Других решений пока нет …