【发布时间】:2013-10-30 10:39:12
【问题描述】:
我的问题与Searching for an array key branch inside a larger array tree - PHP 类似,但有不同的限制(例如动态处理等),为什么不考虑知识,我只想使用 PHP 递归来实现它。
考虑这些数据:
array(
'root_trrreeee1' => array(
'path1' => array(
'description' => 'etc',
'child_of_path_1' => array(
array('name' => '1'),
array('name' => '1')
)
),
'path1' => array(
'description' => 'etc',
'child_of_path_1' => array(
array('name' => '1'),
array('name' => '1')
)
),
),
'name' => '1',
1 => array('name' => '1'),
'another_leaf' => '1'
)
如果我搜索array('name' => '1'),它应该返回我需要遍历的路径以获取该值root_trrreeee1.path1.child_of_path_1.o,最好以数组形式返回:
array(
0 => root_trrreeee1
1 => path1
2 => child_of_path_1
3 => 0
)
这是我尝试实现但不起作用的递归函数:
function multidimensional_preserv_key_search($haystack, $needle, $path = array(), &$true_path = array())
{
if (empty($needle) || empty($haystack)) {
return false;
}
foreach ($haystack as $key => $value) {
foreach ($needle as $skey => $svalue) {
if (is_array($value)) {
$path = multidimensional_preserv_key_search($value, $needle, array($key => $path), $true_path);
}
if (($value === $svalue) && ($key === $skey)) {
$true_path = $path;
return $true_path;
}
}
}
if (is_array($true_path)) { return array_reverse(flatten_keys($true_path)); }
return $path;
}
function flatten_keys($array)
{
$result = array();
foreach($array as $key => $value) {
if(is_array($value)) {
$result[] = $key;
$result = array_merge($result, self::flatten_keys($value));
} else {
$result[] = $key;
}
}
return $result;
}
它只返回一个空数组。 提前致谢。
我发现的类似问题:
- Searching for an array key branch inside a larger array tree - PHP
- Find a value & key in a multidimensional array
- Find all second level keys in multi-dimensional array in php
- Find an array inside another larger array
- How to search by key=>value in a multidimensional array in PHP
- Searching for a key in a multidimensional array then changing a value with PHP
- How can I find the locations of an item in a Python list of lists?
【问题讨论】:
-
你有什么解决办法吗?我被困在同一点上
-
我实现了一个自定义回溯算法:en.wikipedia.org/wiki/Backtracking(页面上的代码)
-
对于那些有同样问题的人,它被称为Backtracking(在算法中)。维基百科上有一个有效的伪代码:en.wikipedia.org/wiki/Backtracking
标签: php arrays algorithm multidimensional-array