Sorting each level of a nested multidimensional PHP array

I have a multidimensional PHP array that I use to create a hierarchical UL tree. However, before displaying the UL tree, I would like to sort each level in the array in alphabetical order using the name attribute. I present a function that recursively checks each level, organizes it in alphabetical order, and moves on to the next level to sort that level. But I do not know how to do this. Any help would be appreciated!

My array:

Array ( [0] => Array ( [id] => 39348 [parent] => 0 [name] => Test [children] => Array ( [0] => Array ( [id] => 41911 [parent] => 39348 [name] => Test2 [children] => Array ( [0] => Array ( [id] => 40929 [parent] => 41911 [name] => Test3 [children] => Array ( [0] => Array ( [id] => 40779 [parent] => 40929 [name] => C ) [1] => Array ( [id] => 40780 [parent] => 40929 [name] => A ) ) ) ) ) 

My attempt, which moves order around, but it is still not alphabetical. Please note: an array ($ this, 'sortByName') is required by CodeIgniter, in which I work:

 function recursive_sort($array) { usort($array, array($this,'sortByName')); foreach($array as $key => $value) { if(isset($value['children']) && !empty($value['children']) && is_array($value['children'])) { $array[$key]['children'] = $this->recursive_sort($value['children']); } } return $array; } function sortByName($a, $b){ return $a->name - $b->name; } 

UPDATE: SOLUTION

 function recursive_sort($array,$child='children') { usort($array,function($a,$b){ return strcasecmp($a['name'], $b['name']); }); foreach($array as $key => $value) { if(isset($value[$child]) && !empty($value[$child]) && is_array($value[$child])) { $array[$key][$child] = $this->recursive_sort($value[$child],$child); } } return $array; } 
+5
source share
1 answer

I typed an algorithmic way of thinking so that you can implement the code yourself. In addition, I would not want to distract all the fun from you !:-)

If this is not enough for you, check this out .

 function example(element) { if (no children exist) return if (only one element exist on this level) // if this code is reached, this element has children example(children element) return names = { array of all name attributes of all elements on this level } sort(names) [0] => names[0] [1] => names[1] .. and so on for however many elements there are return 
+2
source

Source: https://habr.com/ru/post/1239393/


All Articles