Хорошим решением будет рекурсивная функция. Например:
echo "<table>".get_rows($category, 0)."</table>";
function get_rows($arr, $lvl){
$html = '';
foreach ($arr as $array => $innerArray){
$html .= '<tr><td style="padding-left:'.($lvl*30).'px;">'.$innerArray['category_name'].'</td>';
$html .= '<td>'.$innerArray['category_link'].'</td></tr>';
if(isset($innerArray['subcategories'])){
$html .= get_rows($innerArray['subcategories'], $lvl+1);
}
}
return $html;
}
Выход:
cat1 clink
cat11 clink
cat12 clink
cat2 clink
cat21 clink
cat211 clink
cat212 clink
cat2121 clink
cat22 clink
cat3 clink
cat31 clink
cat32 clink
Это вход, который я использовал:
$category = [
[
"category_name"=>"cat1",
"category_link"=>"c1link",
"subcategories"=> [
[
"category_name"=>"cat11",
"category_link"=>"c1link",
"subcategories"=>[]
],
[
"category_name"=>"cat12",
"category_link"=>"c1link",
"subcategories"=>[]
]
],
],
[
"category_name"=>"cat2",
"category_link"=>"c1link",
"subcategories"=> [
[
"category_name"=>"cat21",
"category_link"=>"c1link",
"subcategories"=>[[
"category_name"=>"cat211",
"category_link"=>"c1link",
"subcategories"=>[]
],
[
"category_name"=>"cat212",
"category_link"=>"c1link",
"subcategories"=>[[
"category_name"=>"cat2121",
"category_link"=>"c1link",
"subcategories"=>[]
]]
]]
],
[
"category_name"=>"cat22",
"category_link"=>"c1link",
"subcategories"=>[]
]
]
],
[
"category_name"=>"cat3",
"category_link"=>"c1link",
"subcategories"=> [
[
"category_name"=>"cat31",
"category_link"=>"c1link",
"subcategories"=>[]
],
[
"category_name"=>"cat32",
"category_link"=>"c1link",
"subcategories"=>[]
]
]
]
];