0

I have a big array like:

Array
(
    [1] => Array
        (
            [ID] => 1
            [name] => Product 1
            [productorder] => 7
            [children] => Array
                (
                    [1] => Array
                        (
                            [ID] => 54
                            [name] => Product 1.1
                            [productorder] => 4
                        )

                    [2] => Array
                        (
                            [ID] => 8
                            [name] => Product 1.2
                            [productorder] => 2
                        )
                )
        )
    [2] => Array
        (
            [ID] => 2
            [name] => Product 2
            [productorder] => 1
        )
    [3] => Array
        (
            [ID] => 3
            [name] => Product 3
            [productorder] => 5
        )
)

I need to reorder all the arrays position by the value productorder. It must be recursive via the "children" key, but some of the arrays could not have this key. I tried from this topic:

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

but it's not recursive! Any idea?

1 Answers1

0

Create a function recSortByKey and recursively call the function on the input's children, if present -

function recSortByKey($key = "", $arr = []) {
  // flat
  usort($arr, function($a, $b) {
    return $a[$key] - $b[$key];
  });
  // nested
  if (array_key_exists("children", $arr) && count($arr["children"])) {
    recSortByKey($key, $arr["children"])
  }
}
Mulan
  • 129,518
  • 31
  • 228
  • 259