I have a multidimensional array
which contains a bunch of categories. For this example, I've filled it with clothing categories.
$categories = array(
'Fashion' => array(
'Shirts' => array(
'Sleeve' => array(
'Short sleeve',
'Long sleeve'
),
'Fit' => array(
'Slim fit',
'Regular fit'
),
'Blouse'
),
'Jeans' => array(
'Super skinny',
'Slim',
'Straight cut',
'Loose',
'Boot cut / flare'
)
),
);
I want to be able to print this whole array
like so:
--Fashion
----Shirts
-------Sleeve
---------Short sleeve
---------Long sleeve
-------Fit
---------Slim fit
---------Regular fit
----Blouse
I suppose I need to use some kind of recursive function.
How can I do this?
A recursive function will serve your answer:
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $k => $value) {
printAll($k);
printAll($value);
}
}
try this
<?php
function print_r_recursive($array){
if(!is_array($array)){
echo $array;
return; }
foreach ($array as $value) {
if(is_array($value)){
print_r_recursive($value);
}
}
}
?>
i've tried to use your given array and get this:
$categories = array(
'Fashion' => array(
'Shirts' => array(
'Sleeve' => array(
'Short sleeve',
'Long sleeve'
),
'Fit' => array(
'Slim fit',
'Regular fit'
),
'Blouse'
),
'Jeans' => array(
'Super skinny',
'Slim',
'Straight cut',
'Loose',
'Boot cut / flare'
)
),
);
showCategories($categories);
function showCategories($cats,$depth=1) { // change depth to 0 to remove the first two -
if(!is_array($cats))
return false;
foreach($cats as$key=>$val) {
echo str_repeat("-",$depth*2).(is_string($key)?$key:$val).'<br>'; // updated this line so no warning or notice will get fired
if(is_array($val)) {
$depth++;
showCategories($val,$depth);
$depth--;
}
}
}
will result in
--Fashion
----Shirts
------Sleeve
--------Short sleeve
--------Long sleeve
------Fit
--------Slim fit
--------Regular fit
------Blouse
----Jeans
------Super skinny
------Slim
------Straight cut
------Loose
------Boot cut / flare