John Davidson

php - remove element from a multidimensional array using string index

0 comments
Message:


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
)
)


My Answer:
"Monday" => ["8:00 AM", "10:00 AM"],
"Tuesday" => [],
"Wednesday" => ["9:00 AM", "11:00 AM"],
"Thursday" => [],
"Friday" => ["8:30 AM", "10:30 AM"]
];

To remove the empty schedules (timestamps without any schedule), you can use the following code:

php
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}


This code will iterate through each element in the array and remove the element if the value is empty. After running this code, the updated array will look like this:

php
$array = [
"Monday" => ["8:00 AM", "10:00 AM"],
"Wednesday" => ["9:00 AM", "11:00 AM"],
"Friday" => ["8:30 AM", "10:30 AM"]
];

Rate this post

3 of 5 based on 7705 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us