【发布时间】:2021-05-25 08:35:46
【问题描述】:
我下面有一个多维数组,我想把所有conditions键改成new_child
Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[conditions] => Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[attribute] => category_ids
[conditions] => Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
)
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[conditions] => Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
)
我的预期结果是这样的:
Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[new_child] => Array //change will be made here
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[attribute] => category_ids
[new_child] => Array //change will be made here
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
)
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[new_child] => Array //change will be made here
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
)
我尝试了递归函数,但它不起作用。它只改变父数组,仍然不改变子数组中的键名。
这是我的代码
function convert($input) {
foreach ( $input as $k => &$v )
{
if (array_key_exists('conditions', $input[$k])) {
$input[$k]['new_child'] = $input[$k]['conditions'];
unset($input[$k]['conditions']);
convert($input[$k]['new_child']);
}
}
return $input;
}
print_r(convert($input));
【问题讨论】: