Reputation: 3226
I've category hierarchy like below, but I don't know how to list altough they have PARENTS.
$array[1] = 'A';
$array[1]['children'][1] = 'A1';
$array[1]['children'][2] = 'A2';
$array[2] = 'B';
$array[2]['children'][1] = 'B1';
$array[2]['children'][1]['children'][1] = 'B1-1';
$array[2]['children'][1]['children'][2] = 'B1-2';
It should look like in unsorted list tags (ul > li):
A
A1
A2
B
B1
B1-1
B1-2
So, how can I create this category list using multi-dimensional array?
Upvotes: 2
Views: 677
Reputation: 145512
Since you seemingly do not need any secondary attributes, you should neither start with an enumerated array nor use children
subarrays. In your case you can get away with using the entries as key names:
$hierarchy["A"] = array();
$hierarchy["A"]["A1"] = array();
$hierarchy["A"]["A2"] = array();
$hierarchy["B"] = array();
$hierarchy["B"]["B1"] = array();
$hierarchy["B"]["B2"]["B1-1"] = array();
$hierarchy["B"]["B2"]["B1-2"] = array();
This structure simply assumes that all entries could have children, and hence can be arrays anyway. Note how this can be compacted into:
$hierarchy = array(
"A" => array(
"A1" => array(),
"A2" => array(),
),
"B" => array(
"B1" => array(
"B1-1" => array(),
"B1-2" => array(),
),
),
);
The ordering is retained because PHP arrays are ordered dictionaries anyway.
Iterating over that structure is similar to other variations, except that the actual data is contained in the keys already.
Upvotes: 2
Reputation: 26607
First of all, your array declaration is wrong, you first assign 'A' to $array[1]
, then you try to "transform" $array[1]
in an associative array to add the children.
you can do something like this maybe :
$array[1]['name'] = 'A';
$array[1]['children'][1]['name'] = 'A1';
$array[1]['children'][2]['name'] = 'A2';
$array[2]['name'] = 'B';
$array[2]['children'][1]['name'] = 'B1';
$array[2]['children'][1]['children'][1]['name'] = 'B1-1';
$array[2]['children'][1]['children'][2]['name'] = 'B1-2';
Then, you can show your list with a function like this one :
function make_list($array) {
echo '<ul>';
foreach ($array as $a) {
echo '<li>' . $a['name'];
if (isset($a['children']) && is_array($a['children'])) {
make_list($a['children']);
}
echo '</li>';
}
echo '</ul>';
}
I hope my code is clear.
Upvotes: 2
Reputation: 2611
The proper approach to multi dimensional arrays is using recurrency. Pseudo code would be:
function tree($data){
if (has_kids($data))
return tree($data['kids']);
}
return $data[0];
}
var_dump(tree($data));
Also, to learn about theory check out this article, about tree traversal (multi-dimensional categories are example of trees).
Upvotes: 1