我有一个这样的嵌套数组:
$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']
];
我正在寻找一种在 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>
意味着我希望它看起来像这样:
最佳答案
这是一种使用带有递归函数的纯 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']
];
接下来我们定义一个递归函数,它将为 parent 传递类别标题:
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);
}
}
最后,调用,传递类别树:
printCats($categories);
输出:
<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>
关于php - 将嵌套数组转换为 laravel 中的特定选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483864/