带有路径的PHP数组中的递归搜索 [英] Recursive search in PHP array with path
本文介绍了带有路径的PHP数组中的递归搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个干草堆数组:
$array = [
[
"name" => "Intro",
"id" => "123",
"children" => [
"name" => "foo",
"id" => "234",
"children" => [
"name" => "mur",
"id" => "445",
]
]
],[
"name" => "chapter one",
"id" => "9876",
"children" => [
"name" => "foo",
"id" => "712",
"children" => [
"name" => "bar",
"id" => "888",
]
]
]
];
这个针阵列:$needle = ["chapter one","foo","bar"]
我正在开发一个递归搜索函数,该函数将返回在$needle
路径之后的列name
上匹配的子元素的id
值.
I'm working on a recursive search function that will return the id
value of the child element matching on column name
following the path of $needle
.
在示例中,它应该返回888
.到目前为止,我已经掌握了这一点,但是我没有找到如何跟随$ needle路径,而是假设它们是唯一的,而不是寻找值.感谢所有帮助我步入正轨的帮助.
In the example, it should return 888
. I have this so far but I don't find how to follow the $needle path as opposed to finding values assuming they're unique. Appreciate any help putting me on the right track.
function searchTree( $needle, $haystack, $strict=false, $path=array() )
{
if( !is_array($haystack) ) {
return false;
}
foreach( $haystack as $key => $val ) {
if( is_array($val) && $subPath = searchTree($needle, $val, $strict, $path) ) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
$path[] = $key;
return $path;
}
}
return false;
}
推荐答案
我将尝试对其进行一些清理,但这是可行的:
I'll try to clean it up a bit, but this works:
$needle = ["chapter one", 'foo', 'bar'];
$array = [
[
"name" => "Intro",
"id" => "123",
"children" => [
"name" => "foo",
"id" => "234",
"children" => [
"name" => "mur",
"id" => "445",
]
]
],[
"name" => "chapter one",
"id" => "9876",
"children" => [
"name" => "foo",
"id" => "712",
"children" => [
"name" => "bar",
"id" => "888",
]
]
]
];
function searchTree($needle, $haystack, $strict=false) {
if(!is_array($haystack)) {
return false;
}
$match = false;
if(array_keys($haystack) !== range(0, count($haystack) - 1) && !empty($needle)) {
if(($strict && $haystack['name'] === $needle[0]) || (!$strict && $haystack['name'] == $needle[0])) {
$match = true;
array_shift($needle);
if (!empty($needle)) {
return searchTree($needle, $haystack['children'], $strict);
}
}
} else {
foreach ($haystack as $key => $value) {
if (is_array($value) && !empty($needle)) {
if (($strict && $value['name'] === $needle[0]) || (!$strict && $value['name'] == $needle[0])) {
$match = true;
array_shift($needle);
if (!empty($needle)) {
return searchTree($needle, $value['children'], $strict);
} else {
$haystack = $haystack[$key];
}
}
}
}
}
return (isset($haystack['id']) && $match) ? $haystack['id'] : false;
}
echo searchTree($needle, $array);
输出:
888
这篇关于带有路径的PHP数组中的递归搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文