I have a multidimensional array which are timestamps of school schedules. I want to remove the timestamps that doesn’t have schedule in it, which does make sense.
Array:
$array = [
"06:00 AM - 06:05 AM" => [
0 => 1
],
"06:05 AM - 06:10 AM" => [
1 => 1
]
];
The code I’m trying (which doesn’t work as expected). The goal of the code is to remove the array element with the index of 06:00 AM – 06:05 AM from the multidimensional array.
$toBeRemoved = '06:00 AM - 06:05 AM';
array_walk_recursive($array,
function (&$item, $key, $v) {
if ($item == $v) $item = '';
}, $toBeRemoved);
print_r($array);
Code Output:
As you can see in the output, it doesn’t removed the array element with an index of 06:00 AM – 06:05 AM
Array
(
[06:00 AM - 06:05 AM] => Array
(
[0] => 1
)
[06:05 AM - 06:10 AM] => Array
(
[1] => 1
)
)
Expected Output:
As you can see, the 06:00 AM – 06:05 AM is now gone from the array.
Array
(
[06:05 AM - 06:10 AM] => Array
(
[1] => 1
)
)
4
Answers
array_walk_recursive
Keys having sub array will not passed to this recursive function.recursive doc.
Example:
output:
You may notice that the key ‘sweet’ is never displayed. Any key that holds an array will not be passed to the function.
you may use following code snip
use the unset to remove an element from an associative array
You can try this:
Result: