Home > OS >  remove element from a multidimensional array using string index
remove element from a multidimensional array using string index

Time:10-04

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

CodePudding user response:

use the unset to remove an element from an associative array

$array = [
  "06:00 AM - 06:05 AM" => [
    0 => 1
  ],
  "06:05 AM - 06:10 AM" => [
    1 => 1
  ]
];

unset($array["06:00 AM - 06:05 AM"]);

echo json_encode($array);

CodePudding user response:

$array = [
  "06:00 AM - 06:05 AM" => [
    0 => 1
  ],
  "06:05 AM - 06:10 AM" => [
    1 => 1
  ]
  ];

  $toBeRemoved = '06:00 AM - 06:05 AM';

  $arrayNew = array();

  foreach ($array as $key => $value) {
    if ($key == $toBeRemoved) {
      continue;
    }
    $arrayNew[$key] = $value;
  }

  var_dump($arrayNew);

CodePudding user response:

array_walk_recursive Keys having sub array will not passed to this recursive function.

recursive doc.

Example:

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

output:

a holds apple
b holds banana
sour holds lemon

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

<?php
$result = [
  "06:00 AM - 06:05 AM" => [
    0 => 1
  ],
  "06:05 AM - 06:10 AM" => [
    1 => 1
  ]
];

$toBeRemoved = '06:00 AM - 06:05 AM';

foreach($result as $key => $value){
    if($key == $toBeRemoved ){
        unset($result[$key]);
    }
}

print_r($result);

?>
  • Related