6

I have a multidimensional PHP array that I am using to generate a hierarchical UL tree. However, before displaying the UL tree, I would like to sort each level within the array alphabetically by the 'name' attribute. I am imagining a function that recursively checks each level, organizes it alphabetically, and moves on to the next level to sort that level. But I'm not sure how to do that. 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 is moving the order around, but it is still not alphabetical. Note, the array($this,'sortByName') is required by CodeIgniter, which I am working in:

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;
    }
4
  • 3
    and your attempt is? Commented Dec 29, 2015 at 5:41
  • Check this if it helps : stackoverflow.com/a/3805256/5645769 Commented Dec 29, 2015 at 5:49
  • @TareqMahmood Thank you for the reference. However, the solutions listed for that post only seem to apply to the first level within the multidimensional array. They do not address my situation where I have nested arrays. Commented Dec 29, 2015 at 6:43
  • Your original array and expected output? Commented Dec 29, 2015 at 8:07

1 Answer 1

2

I typed up a an algorithmic way of thinking so you can implement the code yourself. Besides, I wouldn't want to take away all the fun away from you! :-)

If it isn't enough for you, check out this.

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
Sign up to request clarification or add additional context in comments.

4 Comments

@BasheerAhmed what do you even mean by that? You're a confusing person.
@AustinDerrow-Pinion thank you, I have updated my post with my attempt at recursively sorting, but it isn't working right. Maybe you will have some input!
@skiindude22 instead of subtracting the names, use strcmp(string1, string2) function. w3schools.com/php/func_string_strcmp.asp
@AustinDerrow-Pinion strcmp() didn't work, but I did some more research on it, and strcasecmp() wound up doing the trick. Thanks for pointing me in the right direction, it's working now! I have updated my post with the working code.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.