First sort the lines, first the letters, then the letters inside the words

I would like to sort the strings in PHP, and the match should be done primarily on the first letters of the substring, and then on the letters of the whole string.

For example, if someone searches for do and the list contains

 Adolf Doe Done 

the result should be

 Doe Done Adolf 

Using regular sort($array, SORT_STRING) , or similar things do not work, Adolf is sorted before others.

Does anyone have any ideas how to do this?

+7
source share
3 answers

usort(array, callback) allows you to sort based on the callback.

Example

(something like this, have not tried)

 usort($list, function($a, $b) { $posa = strpos(tolower($a), 'do'); $posb = strpos(tolower($b), 'do'); if($posa != 0 && $posb != 0)return strcmp($a, $b); if($posa == 0 && $posb == 0)return strcmp($a, $b); if($posa == 0 && $posb != 0)return -1; if($posa != 0 && $posb == 0)return 1; }); 
+3
source

I would use a custom view:

 <?php $list = ['Adolf', 'Doe', 'Done']; function searchFunc($needle) { return function ($a, $b) use ($needle) { $a_pos = stripos($a, $needle); $b_pos = stripos($b, $needle); # if needle is found in only one of the two strings, sort by that one if ($a_pos === false && $b_pos !== false) return 1; if ($a_pos !== false && $b_pos === false) return -1; # if the positions differ, sort by the first one $diff = $a_pos - $b_pos; # alternatively: $diff = ($b_pos === 0) - ($a_pos === 0) if ($diff) return $diff; # else sort by natural case return strcasecmp($a, $b); }; } usort($list, searchFunc('do')); var_dump($list); 

Output:

 array(3) { [0] => string(3) "Doe" [1] => string(4) "Done" [2] => string(5) "Adolf" } 
+3
source

You can order strings based on stripos($str, $search) so that the first ( stripos() == 0 ) stripos() == 0 first.

The following code pushes the substring positions of the search string into a separate array and then uses array_multisort() to apply the correct ordering to matches; do it this way, not usort() to avoid calling stripos() repeatedly.

 $k = array_map(function($v) use ($search) { return stripos($v, $search); }, $matches); // $k contains all the substring positions of the search string for all matches array_multisort($k, SORT_NUMERIC, $matches, SORT_STRING); // $matches is now sorted against the position 
0
source

All Articles