Ryan Hipkiss
Ryan Hipkiss

Reputation: 678

Sort array and child arrays by value

I have an array like:

$array = array(
    4 => array(
         'position' => 0
         'children' => array(
         )
    ),
    2 => array(
         'position' => 0
         'children' => array(
            3 => array(
                'position' => 1
            )
            5 => array(
                'position' => 0
            )
         )
    )
)

I need to sort the outer arrays (2 & 4) by key 'position', ascending (0 upwards), and then sort each inner array of those ('children'), by their respective position.

There might be 6 main arrays, with 6 'children' arrays to sort.

What is the best way to do this?

Upvotes: 0

Views: 585

Answers (1)

Oleks
Oleks

Reputation: 1633

If I understand your explanation of the problem correctly, following code will work for you:

//sort the outer array
usort($array, function($a, $b) {
    return $a['position'] - $b['position'];
});
//sort childrens
foreach ($array as &$item) {
    usort($item['children'], function($a, $b) {
        return $a['position'] - $b['position'];
    });
}

In any case, usort is a native php function that will be very handy for described case. http://php.net/manual/en/function.usort.php

Upvotes: 2

Related Questions