由于“数据结构”非常模糊,并且您唯一的提示是您使用的是 PHP,我将假设您的“数据结构”含义如下:
[
'USA' =>
[
'Alabama' =>
[
'Montgomery',
'Birmingham'
],
'Arizona' =>
[
'Phoenix',
'Mesa',
'Gilbert'
]
],
'Germany' =>
[
'West Germany' =>
[
'Bonn',
'Cologne'
]
]
]
我假设你希望你的结果在表单中
['USA', 'Alabama', 'Birmingham']
如果不是这种情况,请告知我们您的数据实际上是如何可用的以及您希望得到的结果如何。
在 PHP 中有没有简单的方法来搜索这样的结构?
这取决于您对“简单”的定义。
对我来说,适合单个功能的解决方案是“简单的”。
但是,没有开箱即用的解决方案可以用于单行。
如果您只需要找到“叶子”,您可以使用RecursiveIteratorIterator 而非RecursiveArrayIterator,如this StackOverflow question。
但是由于您也需要找到中间键,所以这不是一个真正的选择。
array_walk_recursive 也是如此。
您可能可以使用ArrayIterator 或array_walk,但在这个例子中,它们实际上并不能做任何foreach 循环不能做的事情,除了复杂的事情。
所以我会选择foreach 循环:
function findMyThing($needle, $haystack) // Keep argument order from PHP array functions
{
// We need to set up a stack array + a while loop to avoid recursive functions for those are evil.
// Recursive functions would also complicate things further in regard of returning.
$stack =
[
[
'prefix' => [],
'value' => $haystack
]
];
// As long as there's still something there, don't stop
while(count($stack) > 0)
{
// Copy the current stack and create a new, empty one
$currentStack = $stack;
$stack = [];
// Work the stack
for($i = 0; $i < count($currentStack); $i++)
{
// Iterate over the actual array
foreach($currentStack[$i]['value'] as $key => $value)
{
// If the value is an array, then
// 1. the key is a string (so we need to match against it)
// 2. we might have to go deeper
if(is_array($value))
{
// We need to build the current prefix list regardless of what we're gonna do below
$prefix = $currentStack[$i]['prefix'];
$prefix[] = $key;
// If the current key, is the one we're looking for, heureka!
if($key == $needle)
{
return $prefix;
}
// Otherwise, push prefix & value onto the stack for the next loop to pick up
else
{
$stack[] =
[
'prefix' => $prefix,
'value' => $value
];
}
}
// If the value is NOT an array, then
// 1. the key is an integer, so we DO NOT want to match against it
// 2. we need to match against the value itself
elseif($value == $needle)
{
// This time append $value, not $key
$prefix = $currentStack[$i]['prefix'];
$prefix[] = $value;
return $prefix;
}
}
}
}
// At this point we searched the entire array and didn't find anything, so we return an empty array
return [];
}
然后像这样使用它
$path = findMyThing('Alabama', $array);