将嵌套数组转换为laravel中的特定选择框

时间:2018-01-28 06:41:59

标签: 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']
];

我正在寻找一种在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>

意味着我希望它看起来像这样:

enter image description here

2 个答案:

答案 0 :(得分:3)

这是一种使用带有递归函数的纯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']
];

接下来,我们定义一个递归函数,它将为父项传递类别标题:

function printCats($categories, $parent = NULL) {
    while ($category = array_shift($categories)) {
        $catName = ($parent ? $parent.' &gt;&gt; ' : '').$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 &gt;&gt; Laptops</option>
<option value='5'>Computers &gt;&gt; Laptops &gt;&gt; PC Laptops</option>
<option value='6'>Computers &gt;&gt; Laptops &gt;&gt; Macbooks (Air/Pro)</option>
<option value='7'>Computers &gt;&gt; Desktops</option>
<option value='8'>Computers &gt;&gt; Monitors</option>
<option value='9'>Cell Phones</option>

答案 1 :(得分:1)

如果您不想自己实施此功能,我过去一直使用此套餐。

https://github.com/atayahmet/laravel-nestable

这将采用嵌套数组/集合并将其转换为HTML列表。对于文档,这是输出的示例:

<select name="categories">
    <option value="1">T-shirts</option>
    <option value="2" selected="selected">  Red T-shirts</option>
    <option value="3">  Black T-shirts</option>

    <option value="4">Sweaters</option>
    <option value="5">  Red Sweaters</option>
    <option value="6">  Blue Sweaters</option>
</select>

它对宏的支持也是一个很好的功能,允许您轻松集成路由。