t.c
t.c

Reputation: 1257

sorting array with uasort comparing to a string with regex

I am trying to sort an array "$refs" by comparing it to a string "$term" using uasort and regex :

this is my array :

Array
(
    [0] => Array
        (
            [id] => 71063
            [uniqid] => A12171063
            [label] => Pratique...
        )

    [1] => Array
        (
            [id] => 71067
            [uniqid] => A12171067
            [label] => Etre....
        )
...

and my code :

uasort($refs, function ($a, $b) use ($term) {
            $patern='/^' . $term . '/';  

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label']) )== 0) {
                return 0;
            }

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == 1) {
                return -1;
            }
            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == -1) {
                return 1;
            }
        });

I have only 0 like returns, where is my mistake !:/ Thanks

Upvotes: 1

Views: 1280

Answers (1)

Orangepill
Orangepill

Reputation: 24655

Won't answer the question as stated but you could use this. It will effectively rank the results based on how close the term is to the beginning of the string.

function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
}

This will only work if all of the values have the term somewhere in them (like the results of a like query).

Test script:

$arr = array("aaTest", "aTest", "AAATest", "Test");
$term = "Test";
uasort($arr, function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
});

print_r($arr);

Test Output:

Array
(
    [3] => Test
    [1] => aTest
    [0] => aaTest
    [2] => AAATest
)

UPDATE

Changed code to use stripos instead of strpos for case insensitive sorting

Upvotes: 3

Related Questions