"Intro", "id" => "123", "children" => [ -6ren">
gpt4 book ai didi

php - 使用路径在 PHP 数组中进行递归搜索

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:11 25 4
gpt4 key购买 nike

我有这个干草堆数组:

$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.

在这个例子中,它应该返回888。到目前为止,我已经有了这个,但我没有找到如何遵循 $needle 路径,而不是假设它们是唯一的来查找值。感谢任何让我走上正轨的帮助。

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;
}

最佳答案

我会尝试稍微清理一下,但这行得通:

$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 - 使用路径在 PHP 数组中进行递归搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com