A.B*_*per 5 php arrays laravel laravel-5.5
我有一个这样的嵌套数组:
$categories = [
['id' => 1, 'name' => 'TV & Home Theather'],
['id' => 2, 'name' => 'Tablets & E-Readers'],
['id' => 3, 'name' => 'Computers', 'children' => [
['id' => 4, 'name' => 'Laptops', 'children' => [
['id' => 5, 'name' => 'PC Laptops'],
['id' => 6, 'name' => 'Macbooks (Air/Pro)']
]],
['id' => 7, 'name' => 'Desktops'],
['id' => 8, 'name' => 'Monitors']
]],
['id' => 9, 'name' => 'Cell Phones']
];
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种在larvel或PHP中将其转换为嵌套组合框的方法,如下所示:
<option value="1">TV & Home Theather</option>
<option value="2">Tablets & E-Readers</option>
<option value="3">Computers</option>
<option value="4">Computers >> Laptops </option>
<option value="5">Computers >> Laptops >> PC Laptops</option>
<option value="6">Computers >> Laptops >> Macbooks (Air/Pro) </option>
<option value="7">Computers >> Desktops </option>
<option value="8">Computers >> Monitors </option>
<option value="9">Cell Phones</option>
Run Code Online (Sandbox Code Playgroud)
意味着我想要它看起来像这样:
这是一种使用纯 PHP 和递归函数来实现这一点的方法......
首先我们定义类别数组:
$categories = [
['id' => 1, 'name' => 'TV & Home Theather'],
['id' => 2, 'name' => 'Tablets & E-Readers'],
['id' => 3, 'name' => 'Computers', 'children' => [
['id' => 4, 'name' => 'Laptops', 'children' => [
['id' => 5, 'name' => 'PC Laptops'],
['id' => 6, 'name' => 'Macbooks (Air/Pro)']
]],
['id' => 7, 'name' => 'Desktops'],
['id' => 8, 'name' => 'Monitors']
]],
['id' => 9, 'name' => 'Cell Phones']
];
Run Code Online (Sandbox Code Playgroud)
接下来我们定义一个递归函数,它将传递父母的类别标题:
function printCats($categories, $parent = NULL) {
while ($category = array_shift($categories)) {
$catName = ($parent ? $parent.' >> ' : '').$category['name'];
print("<option value='{$category['id']}'>{$catName}</option>\n");
if (isset($category['children']))
printCats($category['children'], $catName);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,调用,传递类别树:
printCats($categories);
Run Code Online (Sandbox Code Playgroud)
输出:
<option value='1'>TV & Home Theather</option>
<option value='2'>Tablets & E-Readers</option>
<option value='3'>Computers</option>
<option value='4'>Computers >> Laptops</option>
<option value='5'>Computers >> Laptops >> PC Laptops</option>
<option value='6'>Computers >> Laptops >> Macbooks (Air/Pro)</option>
<option value='7'>Computers >> Desktops</option>
<option value='8'>Computers >> Monitors</option>
<option value='9'>Cell Phones</option>
Run Code Online (Sandbox Code Playgroud)