![](/img/trans.png)
[英]PHP: get subarray of subarray data from array by key from JSON file
[英]php get subarray from array by key
我有下一个层次结构数组:
Array(
[1005] => Array(
[1000] => Array(
[1101] => ...
[1111] => ...
)
)
)
在我的函数中,我发送$ Id。 我的任务是通过此ID返回数组。 例如: getArray(1000)
应该返回下一个数组:
Array(
[1101] => ...
[1111] => ...
)
我该怎么做? 谢谢。
这是getArray
的递归实现:
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;
}
这是getArray
的迭代实现:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.