[英]PHP: How to search for an ID in a tree-like JSON structure recursively and return the path including all previous IDs
我有一个我无法处理的特定问题。 我有一个 JSON 文件,我需要在其中找到 id。 找到 id 时,我需要获取所有以前的 id。
查找 id 51。 结果:51、12962、1101、1100
预先感谢您的帮助。
{
"status":"SUCCESS",
"data":[
{
"id":"12522",
"name":"name 1",
},
{
"id":"13081",
"name":"name 2",
},
{
"id":"1100",
"name":"name 3",
"childs":[
{
"id":"11591",
"name":"name 4",
"childs":[
{
"id":"12382",
"name":"name 5",
},
{
"id":"48",
"name":"name 6",
},
{
"id":"11590",
"name":"name 7",
}
]
},
{
"id":"1101",
"name":"name 8",
"childs":[
{
"id":"11589",
"name":"name 9",
},
{
"id":"12962",
"name":"name 10",
"childs":[
{
"id":"51",
"name":"name 11",
}
]
}
]
}
....
我已经删除了这个示例的 JSON 输入,但结果是一个数组,其中包含 ID 直到您要查找的 id(如果未找到 id,则为空)。 代码带有注释,因此您可以看到它的实际作用。 基本上,我使用的是递归函数,意思是一个调用自身的函数,在每次调用时传递当前的 id 堆栈。
<?php
$data = json_decode( '[{"id": "1234"},{"id": "4567"},{"id": "1100","childs": [{"id": "7890"},{"id": "1101","childs": [{"id": "12962","childs": [{"id": "51"}]}]}]}]' );
// recursively go through the data, searching for the id
function findIdRecursive( $id, $data, $stack = array() ) {
foreach ( $data as $d ) {
// this object corresponds to the id
if ( $d->id === $id ) {
$stack[] = $id;
break;
} else if ( isset( $d->childs ) ) {
// recursively go through this object's children
$childStack = findIdRecursive( $id, $d->childs, $stack );
if( in_array( $id, $childStack ) ) {
// if the id is present in the child stack, return this path
$stack = array_merge( [ $d->id ], $childStack );
break;
}
}
}
return $stack;
}
// [ 51, 12962, 1101, 1100 ]
var_dump( array_reverse( findIdRecursive( "51", $data ) ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.