php通过键从数组中获取子数组
我有下一个层次结构数组:php通过键从数组中获取子数组,php,arrays,recursion,Php,Arrays,Recursion,我有下一个层次结构数组: Array( [1005] => Array( [1000] => Array( [1101] => ... [1111] => ... ) ) ) 在我的函数中,我发送$Id。并通过该Id返回数组。 例如:
Array(
[1005] => Array(
[1000] => Array(
[1101] => ...
[1111] => ...
)
)
)
在我的函数中,我发送$Id。并通过该Id返回数组。
例如:getArray1000应返回下一个数组:
Array(
[1101] => ...
[1111] => ...
)
我怎么做这个?谢谢。下面是getArray的递归实现: 下面是getArray的迭代实现:
以及使用以下公式的答案: 或者,如果你真的想变得有趣,你可以使用:
梅杜?然后,问题应该标记为“task”或“exercice”,或者以某种方式书写,表明这不是个人问题,而是一个exercice。在我的回答中,您实际上可以保留$path数组,并获取任何具有$path[$id]的节点。但出于未知原因,这似乎是一个“不太好的解决方案”。但是,它可以直接解决问题,甚至可以解决这个问题:没有重复的数据,整个过程中只有一个循环通过节点。
function getArray($array, $index) {
if (!is_array($array)) return null;
if (isset($array[$index])) return $array[$index];
foreach ($array as $item) {
$return = getArray($item, $index);
if (!is_null($return)) {
return $return;
}
}
return null;
}
function getArray($array, $index) {
$queue = array($array);
while (($item = array_shift($queue)) !== null) {
if (!is_array($item)) continue;
if (isset($item[$index])) return $item[$index];
$queue = array_merge($queue, $item);
}
return null;
}
function getArray($array, $index) {
$arrayIt = new RecursiveArrayIterator($array);
$it = new RecursiveIteratorIterator(
$arrayIt,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $key => $value) {
if ($key == $index) {
return $value;
}
}
return null;
}
class IndexFilterIterator extends FilterIterator {
protected $index = '';
public function __construct($iterator, $index) {
$this->index = $index;
parent::__construct($iterator);
}
public function accept() {
return parent::key() == $index;
}
}
function getArray($array, $index) {
$arrayIt = new RecursiveArrayIterator($array);
$it = new RecursiveIteratorIterator(
$arrayIt,
RecursiveIteratorIterator::SELF_FIRST
);
$filterIt = new IndexFilterIterator($it, $index);
$filterIt->rewind();
if ($filterIt->valid()) {
return $filterIt->current();
}
return null;
}