根据id获取多维数组路径_如何递归获取多维数组中所有父元素的ID?

Let's say I have the following PHP multidimensional array, which is designed to be recursed through:

$arr = array(

array(

'id' => 1,

'kids' => array(

array(

'id' => 11,

'kids' => array(

array(

'id' => 101,

'kids' => array(),

),

),

), // please note this is a sample

), // it could have any number of levels

),

);

How, given an ID value of 101, can I figure out that IDs 1 and 11 are parents of that element in the multidimensional array?

解决方案

I wrote a function that may be helpful for you.

function get_parents($target, $array)

{

$parents_id = false;

foreach ($array as $item) {

if (empty($array))

return;

if ($item['id'] == $target)

return array();

else

$parents_id = get_parents($target, $item['kids']);

if (is_array($parents_id))

array_unshift($parents_id, $item['id']);

}

return $parents_id;

}

For each item in your array, if it is empty, just return nothing. If it is the item you are looking for, return an empty array in which we will add parent's ids, else keep looking deeper. At this point, if $parents_id is an array, is because you have found your target key, so add parents ids to the beginning of your array

Call this function like this: get_parents('101', $arr);

In your example, the result would be:

Array

(

[0] => 1

[1] => 11

)

If the target key is not found, the function returns false.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值