Set-up:
$array = ['level_one' => [
'level_two' => [
'level_three' => [
'key' => 1
]
]
]];
我为需要遍历每个单独值的过滤过程准备它:
$recurIter = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
问题:
过滤过程完成后,我想将过滤后的$recurIter转换回具有其原始结构的数组。我该怎么做?
到目前为止尝试过:
iterator_to_array($recurIter)
这将返回平展的初始数组:
数组( [键] => 1)
我想要原始结构iterator_to_array仅在应用于递归数组迭代器实例时才返回原始数组结构
谢谢
这行得通吗?
iterator_to_array($recurIter, FALSE)
编辑:
如果您正在进行过滤,您可能会对此感兴趣:
/**
* Select part of a data structure.
*
* @param array|object $data
* The input data to search.
* @param callable $callback
* The callback
* $value - the value of the iterator.
* $key - the key of the iterator.
* $iterator - the iterator can be used to compare against depth + other info.
* @param int $flag
* Flags for RecursiveIteratorIterator -
* http://php.net/manual/en/class.recursiveiteratoriterator.php#recursiveiteratoriterator.constants.
* @param bool $preserve_keys
* If false the returned array of results will have its keys re-indexed
* If true the original keys are kept but duplicate keys can be overwritten.
*
* @return array
* Filtered array.
*/
function recursive_select($data, callable $callback, $flag = RecursiveIteratorIterator::SELF_FIRST, $preserve_keys = FALSE) {
return iterator_to_array(new CallbackFilterIterator(new RecursiveIteratorIterator(new RecursiveObjectIterator($data), $flag), $callback), $preserve_keys);
}
用法:
$selection = recursive_select($array, function ($value, $key, $iterator) : bool {
return $iterator->getDepth() == 2;
});
或
$selection = recursive_select($array, function ($value, $key, $iterator) : bool {
return $key == 'level_two';
});
无论您基本上想要什么条件,都不要因为性能原因而尝试在大型数据集上执行此操作,如果您需要大规模数据过滤,请尽可能使用 SQL,但首先使用 tideways/xhprof 进行基准测试
第二次编辑:我没有看到您希望在过滤器之后保持原样的结构array_walk_recursive()
可能会在这里帮助您
我有同样的需求,但我还没有找到解决方案。
所以我已经构建了自己的函数,也许有人需要它
$array = ['level_one' => [
'level_two' => [
'level_three' => [
'key' => 1
]
]
]];
$new_array = array();
function copy_recursive(&$new_array,$array){
$current =& $new_array;
foreach($array as $key => $val){
//you can also change here the original key name if you want
if (!isset($current[$key])) $current[$key] = array();
if(is_array($val)){
copy_recursive($current[$key],$val);
}else{
//you can check or manipulate here the original value if you need
$current[$key] = $val;
}
}
}
copy_recursive($new_array,$array);
该返回$new_array
具有与原始$array
相同的结构,但这不是从一个数组到另一个数组的简单副本。
您可以为每个key
=> value
应用代码,并将其保存在具有相同结构的$new_array
中