php 递归问题,想要将数据按照无限极分类的样式显示出来
例子:$str='[{"id":1,"name":"lideqi","parentid":0,"childs":[{"id":2,"name":"mahnqiu","pa...
例子:$str = '[{"id":1,"name":"lideqi","parentid":0,"childs":[{"id":2,"name":"mahnqiu","parentid":1,"childs":[{"id":3,"name":"wangxiao","parentid":2},{"id":5,"name":"realy","parentid":2,"childs":[{"id":6,"name":"month","parentid":5}]}]},{"id":7,"name":"dog","parentid":1}]},{"id":4,"name":"good","parentid":0}]';上面是一个json串,其中子节点可能会有很多,例子中只是展示一小部分,想要达到的效果如图:
有层级关系的。。谢谢哦! 展开
有层级关系的。。谢谢哦! 展开
展开全部
首先 将json 解码成数组, 用json_decode 函数 注意 一定要加上第二个参数 否则他会返回一个对象。接下来就是地递归了。这是一个最简单的递归只要逐个遍历即可。
下面是完整的代码:
$data= json_decode($str,true);
$options = getChildren($data);
function getChildren($parent,$deep=0) {
foreach($parent as $row) {
$data[] = array("id"=>$row['id'], "name"=>$row['name'],"pid"=>$row['parentid'],'deep'=>$deep);
if ($row['childs']) {
$data = array_merge($data, getChildren($row['childs'], $deep+1));
}
}
return $data;
}
?>
<select name="" id="">
<?php foreach ($options as $row) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo str_pad("",$row['deep']*3, "-",STR_PAD_RIGHT); ?><?php echo $row['name']; ?></option>
<?php } ?>
</select>
以上代码已测试通过 效果图如下
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询