如何在PHP中取消设置数组的子代值?

时间:2018-08-30 04:30:47

标签: php arrays

我的结构与以下相同:

$sidebar_data= [
    'wp_inactive_widgets' => array(),
    'sidebar-1' => array(
        'this' => 'that',
        'this' => 'that',
        'this' => 'that'
    ),
    'sidebar-2' => array(
        'this' => 'that',
        'this' => 'that',
        'this' => 'that',
        'this' => 'that'
    ),
    'array_version' => 3
];

我希望清除数组键中的所有,而不仅仅是用unset删除整个数组,因此,sidebar-1, sidebar-2应该清空,但要保留,获得所需的结果:

$new_sidebar_data = [
    'wp_inactive_widgets' => array(),
    'sidebar-1' => array(),
    'sidebar-2' => array(),
    'array_version' => 3
];

我该如何实现?

编辑:

我已经经历了以下解决方案:

$sidebar_data= [
    'wp_inactive_widgets' => array(),
    'sidebar-1' => array(
        'this' => 'that',
        'this' => 'that',
        'this' => 'that'
    ),
    'sidebar-2' => array(
        'this' => 'that',
        'this' => 'that',
        'this' => 'that',
        'this' => 'that'
    ),
    'array_version' => 3
];
$sidebars_widgets_original_keys = array_keys( $sidebar_data);
$sidebars_widgets_new_structure = [];

foreach( $sidebars_widgets_original_keys as $sidebars_widgets_original_key ) {
    $sidebars_widgets_new_structure[$sidebars_widgets_original_key] = array();
}

它可以工作,但是真的很难看,向任何人展示都是违反直觉的。

2 个答案:

答案 0 :(得分:1)

您可以重新分配空数组

$new_sidebar_data['sidebar-1'] = [];
$new_sidebar_data['sidebar-2'] = [];

更多动态方式

foreach($new_sidebar_data as &$value) {
    if (is_array($value) && count($value) > 0) {
         $value = [];
    }
}

答案 1 :(得分:1)

另一个适合您的选择

array_walk($new_sidebar_data, function (&$value, $key) {
    if (is_array($value) && count($value) > 0) {
        $value = [];
    }
});

适用于所有以“ sidebar-”开头的键