0

I'm trying to sort the second-level values based on a specific keyword. In this case that keyword is red.

If I inspect the steps in the callback function it seems to work, but the final result is unchanged. It also sorts the top-level keys alphabetically.

$data = array(
    'foo' => array(
        'red', 'green'
    ),
    'bar' => array(
        'yellow', 'red'
    ),
);

print_r($data);

uasort($data, function($data) {
    $matches = preg_grep("/red/", $data);

    $rest = array_diff($data, $matches);

    $order = array_merge($matches, $rest);

    return $order;

});

print_r($data);
1
  • What is the desired result? Do we have enough sample data to verify correct answers? Commented Feb 2 at 14:40

1 Answer 1

2

Your code doesn't work as intended because uasort() only sorts the array you pass to it in the first argument, the first level array ($data). The rest of your code, although running and syntactically correct, does not help either.

Here is a working example :

$data = array(
    'foo' => array(
        'red', 'green'
    ),
    'bar' => array(
        'yellow', 'red'
    ),
);

array_walk($data,function(&$v){
    uasort($v,function($a,$b){
        return preg_match('/red/',$a)?-1:1;
});});

print_r($data);
  • array_walks() iterates through the first-level array.
  • uasort() is provided in the callback, and handles the sorting part of the second-level arrays.
  • preg_match() is then used to match the string and return a value suitable for reordering in the callback to uasort().
Sign up to request clarification or add additional context in comments.

1 Comment

function($a,$b){ return preg_match('/red/',$a)?-1:1; } makes NO sense -- there is no $b evaluation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.