PHP | 以递归方式清空数组的所有值,但保留所有键
问题描述:
I want to empty all values by empty string in a PHP array, and keeping all the keys names recursively.
Example:
<?php
$input =
['abc'=> 123,
'def'=> ['456', '789', [
'ijk' => '555']
]
];
I want my array to become like this:
<?php
$output = ['abc'=> '',
'def'=> ['', '', [
'ijk' => '']
]
];
我想在PHP数组中用空字符串清空所有值,并递归保存所有键名。 p>
示例: p>
&lt;?php
$ input =
['abc'=&gt; 123,
'def'=&gt; ['456','789',[
'ijk'=&gt; '555']
]
];
code> pre>
我希望我的数组变成这样: p>
&lt;?php
$ output = ['abc'=&gt; '',
'def'=&gt; ['','',[
'ijk'=&gt; '']
]
];
code> pre>
div>
答
You should use recursive function:
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;
}
And just call this function with your array as the only parameter:
$input = [
'abc' => 123,
'def' => [
'456',
'789', [
'ijk' => '555',
],
],
];
$output = setEmpty($input);