【发布时间】:2015-10-02 08:59:03
【问题描述】:
我正在尝试编写一个 sn-p,它采用多维数组并在找到命名搜索键的同一级别插入一些键。 我不必依赖数组的结构(但最多5个级别) 我不能使用通过引用传递,所以传统的循环函数对这种方法没有帮助。
我有 2 个选项:SPL 或重新构造数组并沿途改变它的递归
使用 SPL,我似乎无法插入新值..
$a= new \ArrayObject($priceConfig);
$array = new \RecursiveArrayIterator($a);
$iterator = new \RecursiveIteratorIterator($array, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (is_array($value) && $key == 'prices') {
$iterator->offsetSet('myPrice',['amount'=>'1.00']);
}
}
print_r($a->getArrayCopy());
它不会在所需级别插入新密钥,但它会循环遍历数组..我错过了什么?
重构数组并在嵌套数组中的关键字搜索中插入新值的递归函数有效,但我想使用迭代器来执行此操作..
function recursive( $input, $searchKey, $key=null) {
$holder = array();
if(is_array( $input)) {
foreach( $input as $key => $el) {
if (is_array($el)) {
$holder[$key] = recursive($el, $searchKey, $key);
if ($key == $searchKey) {
$holder[$key]['inertedPrice'] = "value";
}
} else {
$holder[$key] = $el;
}
}
}
return $holder;
}
INPUT(总是有一些“X 级别的价格键和结构”)
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
)
[key] => value
)
)
)
输出
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
[INSERTEDPrice] => Array([amount] => value)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
[INSERTEDPrice] => Array([amount] => )
)
[key] => value
)
)
)
【问题讨论】:
-
请包含示例输入和输出,以便我们更好地理解问题。
-
添加所需的输出并提供输入
标签: php arrays recursion multidimensional-array spl