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.
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 = [];
}
}
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-"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.