二维数组递归调用生成 HTML select列表

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$data = [
['id' => 1, 'parent_id' => 0, 'dpath' => 1, 'name' => '服装'],
['id' => 2, 'parent_id' => 1, 'dpath' => 2, 'name' => '男士服装'],
['id' => 3, 'parent_id' => 2, 'dpath' => 3, 'name' => '外套'],
['id' => 4, 'parent_id' => 2, 'dpath' => 3, 'name' => '裤子'],
['id' => 5, 'parent_id' => 0, 'dpath' => 1, 'name' => '家用电器'],
['id' => 6, 'parent_id' => 5, 'dpath' => 2, 'name' => '冰箱'],
['id' => 7, 'parent_id' => 6, 'dpath' => 3, 'name' => '海尔冰箱'],
['id' => 8, 'parent_id' => 5, 'dpath' => 2, 'name' => '空调'],
['id' => 9, 'parent_id' => 8, 'dpath' => 3, 'name' => '格力空调']
];

将数组处理成,如下格式:

无限级分类

具体 PHP 实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
function selectHtml($data, $name, $select_id = null)
{
$options = data2options($data, 0, '', $select_id);
return '<select name="'. $name .'" class="form-control">' . $options . '</select>';
}

function data2options($data, $pid=0, $options = '', $select_id)
{
foreach($data as $k=>$v){
if($v['parent_id'] == $pid){
$options .= '<option value="' . $v['id'] . '"' . ($select_id && $select_id == $v['id'] ? 'selected' : '') . '>'
. ($v['dpath'] != 1 ? '|' : '') . str_repeat('----', $v['dpath'] - 1) . $v['name'] . '</option>';
unset($data[$k]);
$options = data2options($data, $v['id'], $options, $select_id);
}
}
return $options;
}

$selectHtml = selectHtml($data, 'category_id', false, null);
echo $selectHtml;