我想在PHP数组中用空字符串清空所有值,并递归保存所有键名。
示例:
<?php
$input =
['abc'=> 123,
'def'=> ['456', '789', [
'ijk' => '555']
]
];
我希望我的阵列变成这样:
<?php
$output = ['abc'=> '',
'def'=> ['', '', [
'ijk' => '']
]
];
答案 0 :(得分:4)
你应该使用递归函数:
function setEmpty($arr)
{
$result = [];
foreach($arr as $k=>$v){
/*
* if current element is an array,
* then call function again with current element as parameter,
* else set element with key $k as empty string ''
*/
$result[$k] = is_array($v) ? setEmpty($v) : '';
}
return $result;
}
只需将您的数组作为唯一参数调用此函数:
$input = [
'abc' => 123,
'def' => [
'456',
'789', [
'ijk' => '555',
],
],
];
$output = setEmpty($input);