I Have the following Array and I would like to sort it based on the $term = "geo" in relation only to [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
)
)
The desired result should be:
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
)
)
I have tried various methods such as:
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;
});
and
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);
});
and
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);
});
and
usort($data, function($a, $b){ return $a["result_title"] - $b["result_title"]; });
and many more without any proper result. Or maybe I cannot understand the method to achieve my result?
I have also checked: php sorting an array based on a string and How to sort an array by similarity in relation to an inputted word. but the answers are giving me the result I'm looking for.