猿问

php树获取子节点的所有父节点的列表

我想要子节点的所有父节点的列表。我正在搜索,但我正在获取父节点的所有子节点。我的数组看起来像


array(

array('id' => 1, 'parent' => 0),

array('id' => 2, 'parent' => 0),

array('id' => 3, 'parent' => 0),

array('id' => 4, 'parent' => 1),

array('id' => 5, 'parent' => 4),

array('id' => 6, 'parent' => 5));

我想要的输出是,我给输入子节点 Id ,它将返回所有父节点。例如,我将给孩子 ID“raja”,它将给出输出 1) manish 2) vijay 3) admin。



元芳怎么了
浏览 232回答 2
2回答

凤凰求蛊

看看这个例子,让我知道这是否是您正在寻找的。<?php&nbsp;$arr = array(&nbsp; &nbsp; array('id' => 1, 'parent' => 0),&nbsp; &nbsp; array('id' => 2, 'parent' => 0),&nbsp; &nbsp; array('id' => 3, 'parent' => 0),&nbsp; &nbsp; array('id' => 4, 'parent' => 1),&nbsp; &nbsp; array('id' => 5, 'parent' => 4),&nbsp; &nbsp; array('id' => 6, 'parent' => 5));$parents = [];function find_parents($input, $id) {&nbsp; &nbsp; global $parents, $arr;&nbsp; &nbsp; if(is_array($input)) {&nbsp; &nbsp; &nbsp; &nbsp; foreach($input as $k => $val) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($val['id'] == $id&nbsp; && $val['parent'] != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_push($parents, $val['parent']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; find_parents($arr, $val['parent']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}find_parents($arr, 6);print_r($parents);作为6输入将输出Array(&nbsp; &nbsp; [0] => 5&nbsp; &nbsp; [1] => 4&nbsp; &nbsp; [2] => 1)您可以使用递归,以便它可以使用到任何级别。无需限制级别。

慕娘9325324

&nbsp;&nbsp;&nbsp;&nbsp;find_parents($arr,&nbsp;$val['parent']);在上面的行中,递归参数中的 $arr 应该是 $input 数组变量。
随时随地看视频慕课网APP
我要回答