$data = array(
array('id' => 1, 'title' => '衣服', 'parent' => 0),
array('id' => 2, 'title' => '鞋子', 'parent' => 0),
array('id' => 3, 'title' => '衬衫', 'parent' => 1),
array('id' => 4, 'title' => 'T恤', 'parent' => 1),
array('id' => 5, 'title' => '运动鞋', 'parent' => 2),
array('id' => 6, 'title' => '休闲鞋', 'parent' => 2),
);
$data2 = array(
array('id' => 1, 'title' => '食物', 'parent' => 0),
array('id' => 2, 'title' => '肉食', 'parent' => 1),
array('id' => 3, 'title' => '素食', 'parent' => 1),
array('id' => 4, 'title' => '牛肉', 'parent' => 2),
array('id' => 5, 'title' => '面条', 'parent' => 3),
array('id' => 6, 'title' => '馒头', 'parent' => 3),
);
//生成树型数据
function genTree($items, $id = 'id', $pid = 'parent', $son = 'child') {
$tree = array();
$tmpMap = array();
foreach ($items as $item) {
$tmpMap[$item[$id]] = $item;
}
foreach ($items as $item) {
if (isset($tmpMap[$item[$pid]])) {
$tmpMap[$item[$pid]][$son][] = $tmpMap[$item[$id]];
} else {
$tree[] = $tmpMap[$item[$id]];
}
}
unset($tmpMap);
return $tree;
}
//通过给定数据,返回option的字符串,用于select下拉框
function getOpts($data, $idArr = array(), $level = 0, $son = 'child') {
static $opt = '';
if (!empty($data)) {
foreach ($data as $k => $v) {
$opt .= 'option value=' . $v['id'] . (in_array($v['id'], $idArr) ? ' selected="true"' : '') . '>' . str_repeat(' ', $level * 3) . $v['title'] . '/option>';
if (!empty($v[$son])) {
getOpts($v[$son], $idArr, $level + 1, $son);
}
}
}
return $opt;
}
$data = genTree($data);
echo 'select>';
//第一次调用getOpts时,没有任何问题。
echo getOpts($data);
echo '/select>';
$data2 = genTree($data2);
echo 'select>';
//当第二次调用时,问题就出现了,还留有上次的数据
echo getOpts($data2);
echo '/select>';
function getOpts($data, $idArr = array(), $opt = '', $level = 0, $son = 'child') {
if (!empty($data)) {
foreach ($data as $k => $v) {
$opt .= 'option value=' . $v['id'] . (in_array($v['id'], $idArr) ? ' selected="true"' : '') . '>' . str_repeat(' ', $level * 3) . $v['title'] . '/option>';
if (!empty($v[$son])) {
getOpts($v[$son], $idArr, $opt, $level + 1, $son);
}
}
}
}
$data = genTree($data);
getOpts($data, array(), $opt);
echo 'select>';
echo $opt;
echo '/select>';
$data2 = genTree($data2);
getOpts($data2, array(), $opt2);
echo 'select>';
echo $opt2;
echo '/select>';
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php常用函数与技巧总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》及《php程序设计算法总结》