Home > Software engineering >  How to remove subarray in multidimensional array if exsits the same values in other array
How to remove subarray in multidimensional array if exsits the same values in other array

Time:03-14

I have two multidimensional arrays:

Array A
(
    [0] => Array
        (
            [reservation_start] => 08:00:00
            [reservation_end] => 08:35:00
        )

    [1] => Array
        (
            [reservation_start] => 08:35:00
            [reservation_end] => 09:10:00
        )

    [2] => Array
        (
            [reservation_start] => 09:10:00
            [reservation_end] => 09:45:00
        )
)

Array B
(
    [0] => Array
        (
            [reservation_start] => 08:00:00
            [reservation_end] => 08:35:00
        )

    [1] => Array
        (
            [reservation_start] => 08:35:00
            [reservation_end] => 09:10:00
        )

)

foreach loop:

foreach ($allHours as $key => $value) {
    if (in_array($value, $busyHours)) {
        unset($allHours[$key]);
    }
}

And now I would like to remove from array A values exists in array. I used unset in foreach, but in each time arrays have different size so it does not work

CodePudding user response:

$array1 = [
    [ 'start' => '08:00:00', 'end' => '08:35:00' ],
    [ 'start' => '08:35:00', 'end' => '09:10:00' ],
    [ 'start' => '09:10:00', 'end' => '09:45:00' ]
];

$array2 = [
    [ 'start' => '08:00:00', 'end' => '08:35:00' ],
    [ 'start' => '08:35:00', 'end' => '09:10:00' ]
];

$result = [];

array_walk($array1, function ($value1, $index1) use (&$result, $array2) {
  array_walk($array2, function ($value2, $index2) use (&$result, $value1) {
    if ($value1['start'] === $value2['start'] && $value1['end'] === $value2['end']) {
      $result[] = $value1;
    }
  });
});

print_r($result);

Output:

Array
(
    [0] => Array
        (
            [start] => 08:00:00
            [end] => 08:35:00
        )

    [1] => Array
        (
            [start] => 08:35:00
            [end] => 09:10:00
        )

)

CodePudding user response:

assuming arrays A = allhours B = busyhours

  • stringfy both & reduce to 1-dimensional array

    foreach ($all as $k=>$arr) {
        $all_copy[$k] = $arr['reservation_start'] . $arr['reservation_end'];
    }

    foreach ($busy as $k=>$arr) {
        $busy_copy[$k] = $arr['reservation_start'] . $arr['reservation_end'];
    }

    // array_diff preserves keys.
    $non_busy = array_diff($all_copy, $busy_copy);
  • get resultant array from the original all
foreach ($non_busy as $k=>$no_need)
{
   $result[$k] = $all[$k];
}

  • you may unset arrays that you won't need anymore except $result
  • Related