JSON:http://pastebin.com/XjK1VKE3
我需要遍历每个类别并创建一个嵌套列表,如下所示:
Electronics(31110)
Mobile & Accessories(31087)
Mobile Accessories(31080)
Cases & Covers(29808)
Screen Guards(729)
Mobile Accessories Combos(355)
Cables(153)
Chargers(21)
Power Banks(9)
Batteries(2)
Selfie Stick(2)
Mobile Lenses(1)
Mobiles(7)
Computers & Accessories(15)
...
...
我的代码开始变丑:
if ($object->frontend_filters[0]->values->cats) {
foreach ($object->frontend_filters[0]->values->cats as $cat) {
echo print_r($cat,1);
if ($cat->cats) {
foreach ($cat->cats as $subcat) {
if ($subcat->cats) {
foreach ($subcat->cats as $subcat3) {
$results['categories'][$cat->name][$subcat->name][] = $subcat3->name;
}
}
else {
$results['categories'][$cat->name][] = $subcat->name;
}
}
}
else {
$results['categories'][$cat->name] = [];
}
}
}
如何在不创建n
次循环的情况下执行此操作,因为我不确定每次可能有多少级别。
答案 0 :(得分:0)
使用以下功能,请参阅演示here:
// convert your json to a php array
$data = json_decode($yourJson,true);
function doList($data)
{
echo "<ul>";
foreach($data as $i =>$value)
{
if(is_array($value))
{
doList($value);
}
else
{
if($i == 'name' && $value != 'All')
{
echo "<li>$value({$data['count']})</li>";
}
}
}
echo '</ul>';
}
doList($data);