Mae*_*aeh 2 php arrays recursion
我有一个多维array
,其中包含一堆类别.在这个例子中,我已经填写了服装类别.
$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'
)
),
);
Run Code Online (Sandbox Code Playgroud)
我希望能够array
像这样打印这整个:
--Fashion
----Shirts
-------Sleeve
---------Short sleeve
---------Long sleeve
-------Fit
---------Slim fit
---------Regular fit
----Blouse
Run Code Online (Sandbox Code Playgroud)
我想我需要使用某种递归函数.
我怎样才能做到这一点?
我试图使用你给定的数组并得到这个:
$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--;
}
}
}
Run Code Online (Sandbox Code Playgroud)
会导致
--Fashion
----Shirts
------Sleeve
--------Short sleeve
--------Long sleeve
------Fit
--------Slim fit
--------Regular fit
------Blouse
----Jeans
------Super skinny
------Slim
------Straight cut
------Loose
------Boot cut / flare
Run Code Online (Sandbox Code Playgroud)