-1

I have a structure identical to:

$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
];

I'm looking to wipe out any values within the array's keys, not just the full array with unset, so, sidebar-1, sidebar-2 should be emptied, but kept, to get the desired result:

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

How can I achieve this?

Edit:

I already went through this solution:

$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();
}

It works, but it's really ugly and feels counterintuitive to present to anyone.

coolpasta
  • 725
  • 5
  • 19
  • All keys, or all keys not including `array_version`, or all keys which are arrays, or ??? – Nick Aug 30 '18 at 04:36
  • @Nick It doesn't matter in this case, should just keep the keys. – coolpasta Aug 30 '18 at 04:41
  • @Erubiel Not a duplicate. I'm looking to keep the keys of the array. – coolpasta Aug 30 '18 at 04:42
  • yeah, but you can manage each children on the same way, if you are asking for the best way... but maybe you are right, maybe i should have posted it as a comment sorry... – Erubiel Aug 30 '18 at 04:43

2 Answers2

1

You can reassign empty array

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

more dynamic way

foreach($new_sidebar_data as &$value) {
    if (is_array($value) && count($value) > 0) {
         $value = [];
    }
}
Jasmin Mistry
  • 1,459
  • 1
  • 18
  • 23
1

Another option for you

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

Works for all keys starting with "sidebar-"

bbbbburton
  • 63
  • 7