PHP |以递归方式清空数组的所有值,但保留所有键

时间:2017-03-19 08:42:44

标签: php arrays

我想在PHP数组中用空字符串清空所有值,并递归保存所有键名。

示例:

<?php
$input = 
['abc'=> 123,
    'def'=> ['456', '789', [
    'ijk' => '555']
    ]
];

我希望我的阵列变成这样:

<?php
$output = ['abc'=> '',
    'def'=> ['', '', [
        'ijk' => '']
      ]
];

1 个答案:

答案 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);
相关问题