3

I have this array:

$animals = array(
    '0' => array('name' => 'cat', 'order' => '2'),
    '1' => array('name' => 'dog', 'order' => '1'),
    '2' => array('name' => 'fish', 'order' => '3')
);

I want to turn it into this:

$animals = array(
    '1' => array('name' => 'dog', 'order' => '1'),
    '0' => array('name' => 'cat', 'order' => '2'),
    '2' => array('name' => 'fish', 'order' => '3')
);

As you can see I want to sort based on the order key. How to do this?

2
  • Joe...maybe because he wants to display results in a certain order?? Why else would you ever want to sort anything? Commented Jun 12, 2013 at 20:27
  • @joe right now when I foreach over $animals I get it in this order: cat, dog, fish. I want it in the right order based on the order key. Unfortunately I don't have control over the code when the array gets built initially. Commented Jun 12, 2013 at 20:27

3 Answers 3

3

Use PHP's native usort function with a userdefined callback reading the order fields.

If maintaining index association is critical use uasort instead.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use array_multisort()

 $animals = array(
    '0' => array('name' => 'cat', 'order' => '2'),
    '1' => array('name' => 'dog', 'order' => '1'),
    '2' => array('name' => 'fish', 'order' => '3')
);

$tmp = array();
foreach($animals as $k=>$r){
    $tmp[] = $r['order'];
}
array_multisort($tmp,SORT_ASC,$animals); // SORT_DESC to reverse

echo '<pre>',print_r($animals),'</pre>';

Comments

1

Try this...using usort()

$animals = array(
'0' => array('name' => 'cat', 'order' => '2'),
'1' => array('name' => 'dog', 'order' => '1'),
'2' => array('name' => 'fish', 'order' => '3')
);


function build_sorter($key) {
   return function ($a, $b) use ($key) {
       return strnatcmp($a[$key], $b[$key]);
   };
}

usort($animals, build_sorter('order'));

var_dump($animals);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.