如何从多维数组中取消设置名为id
的所有键?
private function remove_id(Array &$arr){
foreach($arr as $key => $value){
if($key == 'id'){
unset($arr[$key]);
}
elseif(is_array($value)){
$this->remove_id($value);
}
}
}
Array
(
[id] => 52453
[periods] => Array
(
[0] => Array
(
[id] => 95296
[is_readonly] => 0
[year] => 2016
[month] => 1
)
[1] => Array
(
[id] => 95297
[is_readonly] => 0
[year] => 2016
[month] => 2
)
[2] => Array
(
[id] => 95298
[is_readonly] => 0
[year] => 2016
[month] => 3
)
[3] => Array
(
[id] => 95299
[is_readonly] => 0
[year] => 2016
[month] => 4
)
[4] => Array
(
[id] => 95300
[is_readonly] => 0
[year] => 2016
[month] => 5
)
[5] => Array
(
[id] => 95301
[is_readonly] => 0
[year] => 2016
[month] => 6
)
[6] => Array
(
[id] => 95302
[is_readonly] => 0
[year] => 2016
[month] => 7
)
[7] => Array
(
[id] => 95303
[is_readonly] => 0
[year] => 2016
[month] => 8
)
[8] => Array
(
[id] => 95304
[is_readonly] => 0
[year] => 2016
[month] => 9
)
[9] => Array
(
[id] => 95305
[is_readonly] => 0
[year] => 2016
[month] => 10
)
[10] => Array
(
[id] => 95306
[is_readonly] => 0
[year] => 2016
[month] => 11
)
[11] => Array
(
[id] => 95307
[is_readonly] => 0
[year] => 2016
[month] => 12
)
)
[closing_profit_amount] => 0
[closing_profit_net_amount] => 0
)
答案 0 :(得分:4)
您需要在&value
循环中使用for
来保持嵌套数组的更改。
此外,数组不能超过1个id
键,因此无需在循环中检查它,这样可以进行一些微优化:
private function remove_id(Array &$arr){
if(isset($arr['id'])) {
unset($arr['id']);
}
foreach($arr as &$value){
if(is_array($value)){
$this->remove_id($value);
}
}
}