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

标签 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

最佳答案

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

关于php - 将嵌套数组转换为 laravel 中的特定选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483864/

相关文章:

PHP 变量在 Wordpress 头文件和索引文件中不起作用?

php - Codeigniter MY_Model 类

arrays - VBA:创建类模块数组

Laravel 5.1 随机丢弃 session 数据

php - 如何在php中转义xpath

php - 将 javascript 与 htaccess 和 php 捆绑在一起

c - 如何将 void** 数组(函数的返回值)分配给变量?

javascript - 删除一项后组件列表不更新状态

laravel - smtp 中继 - g 套件 - 带有自定义域电子邮件的 gmail

php - 使用 Laravel 5 将数据从旧表转移到新表