Giedrius Pirmasis Giedrius Pirmasis - 8 months ago 70
PHP Question

Sorting specific multidimensional nested array level by under element value name

I have array structure which looks like this.

Array
(
[category1] => Array
(
[2694] => Array
(
[node_name] => "B"

)

[2695] => Array
(
[node_name] => "A"

)
[2696] => Array
(
[node_name] => "C"

)
)
)


I want parent array with number by node name. The expected result should be like this.

Array
(
[category1] => Array
(
[2695] => Array
(
[node_name] => "A"

)

[2694] => Array
(
[node_name] => "B"

)
[2696] => Array
(
[node_name] => "C"

)
)
)


I have tried multisort and uasort using funcion

function cmp($a, $b) {
return $a['node_name'] > $b['node_name'] ? 1 : -1;
}


But there is a multiple categories that should be taken in mind, so I tried to iterate categories and use uasort or multisort on the inner elements. Not sure hows should I approach this problem so I was wondering if anyone has experience solving nested arrays and sorting a specific level based on name of the under elements.

Any help would be appreciated.

Answer Source

You're doing the right thing I expect.

<?php

$cats = array(
  'category1' => array(
    2694 => array('node_name' => 'B'),
    2695 => array('node_name' => 'A'),
    2696 => array('node_name' => 'C'),
  ),
  'category2' => array(
    2691 => array('node_name' => 'T'),
    2692 => array('node_name' => 'S'),
    2693 => array('node_name' => 'A'),
  )
);

function cmp($a, $b) {
    return $a['node_name'] > $b['node_name'] ? 1 : -1;
}

foreach ($cats as $category => $data) {
   uasort($data, 'cmp');
   $cats[$category] = $data;
}

var_dump($cats);

Output:

array(2) {
  ["category1"]=>
  array(3) {
    [2695]=>
    array(1) {
      ["node_name"]=>
      string(1) "A"
    }
    [2694]=>
    array(1) {
      ["node_name"]=>
      string(1) "B"
    }
    [2696]=>
    array(1) {
      ["node_name"]=>
      string(1) "C"
    }
  }
  ["category2"]=>
  array(3) {
    [2693]=>
    array(1) {
      ["node_name"]=>
      string(1) "A"
    }
    [2692]=>
    array(1) {
      ["node_name"]=>
      string(1) "S"
    }
    [2691]=>
    array(1) {
      ["node_name"]=>
      string(1) "T"
    }
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download