samedi 27 juin 2015

Sorting infinite depth array - php

I have the following array: (ordered by parent_id)

array(9) {
  [1]=>
  array(3) {
    ["name"]=>
    string(6) "Tennis"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [7]=>
  array(3) {
    ["name"]=>
    string(11) "TOP LEVEL 2"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [8]=>
  array(3) {
    ["name"]=>
    string(11) "TOP LEVEL 3"
    ["parent_id"]=>
    NULL
    ["depth"]=>
    int(0)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(5) "Shoes"
    ["parent_id"]=>
    string(1) "1"
    ["depth"]=>
    int(1)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "Women"
    ["parent_id"]=>
    string(1) "2"
    ["depth"]=>
    int(2)
  }
  [4]=>
  array(3) {
    ["name"]=>
    string(4) "Mens"
    ["parent_id"]=>
    string(1) "2"
    ["depth"]=>
    int(2)
  }
  [5]=>
  array(3) {
    ["name"]=>
    string(12) "Mens Running"
    ["parent_id"]=>
    string(1) "4"
    ["depth"]=>
    int(3)
  }
  [6]=>
  array(3) {
    ["name"]=>
    string(11) "Mens Tennis"
    ["parent_id"]=>
    string(1) "4"
    ["depth"]=>
    int(3)
  }
  [9]=>
  array(3) {
    ["name"]=>
    string(9) "2nd level"
    ["parent_id"]=>
    string(1) "8"
    ["depth"]=>
    int(1)
  }
}

I want to sort it in a way that it can be used in a drop down menu. The format for a drop down menu is:

$categories[$CATEGORY_ID] = str_repeat('  ', $value['depth']).$value['name'];

The above array up top is sorted by parent_id where top levels have a parent_id of NULL.

I need to sort it in such a way that the array is in order. For example:

[1] => 'Tennis';
[2] => ' &nbspShoes'
[3] => '     Womens'
[4] => '     Men'
[5] => '      Mens Running
[6] => '      Mens Tennis
[7] => 'TOP LEVEL 2'
[8] => 'TOP LEVEL 3'
[9] => '  2nd level'

Aucun commentaire:

Enregistrer un commentaire