Home > Mobile >  How to get the values of array if it does not exist in the other array
How to get the values of array if it does not exist in the other array

Time:02-23

I want to get the dates of my arrays if it does not exist on the other array. Its a simple logic but I can't do it

variable values

$date_ranges:

array:5[    
0 => "2022-02-22 08:00:00"
1 => "2022-02-23 08:00:00"
2 => "2022-02-24 08:00:00" 
3 => "2022-02-25 08:00:00"
4 => "2022-02-26 08:00:00"
]

$results:

0 => array:2[
"name" => "Steve"
"start_date" => "2022-02-22 08:00:00"
]

1 => array:2[
"name" => "Chelsea"
"start_date" => "2022-02-24 08:00:00"
]

2 => array:2[
"name" => "Azu"
"start_date" => "2022-02-26 08:00:00"
]

I'm having problems getting my expected output I want to store the dates of $date_ranges that does not exist on the $results as array.

Expected dates to get: 2022-02-23 08:00:00 and 2022-02-25 08:00:00

array:2[
0 => "2022-02-23 08:00:00"
1 => "2022-02-25 08:00:00"

]

CodePudding user response:

An example using $hash_map_times to store a HashMap to avoid unnecessary loop.

Sandbox

<?php

$input = [
    "2022-02-22 08:00:00",
    "2022-02-23 08:00:00",
    "2022-02-24 08:00:00",
    "2022-02-25 08:00:00",
    "2022-02-26 08:00:00"
];

$times = [
    [
        "name" => "Steve",
        "start_date" => "2022-02-22 08:00:00"
    ],
    [
        "name" => "Chelsea",
        "start_date" => "2022-02-24 08:00:00"
    ],
    [
        "name" => "Azu",
        "start_date" => "2022-02-26 08:00:00"
    ]
];

$hash_map_times = array_reduce($times, function ($carry, $item) {
    $start_date = $item["start_date"];
    if (!isset($carry[$start_date])) {
        $carry[$start_date] = 1;
    }
    return $carry;
}, []);

$output = array_reduce($input, function ($carry, $item) use ($hash_map_times) {
    if (!isset($hash_map_times[$item])) {
        $carry[] = $item;
    }
    return $carry;
}, []);

print_r($output);

CodePudding user response:

use below code:

$resultArray = [];

foreach ($date_ranges as $dateRange) {
    if (!in_array($dateRange, array_column($results, 'start_date'))) {
        array_push($resultArray, $dateRange);
    }
}

CodePudding user response:

Using array_filter could work.

$filtered = array_filter(
    $date_ranges,
    function ($item) {
        return in_array($item, array_column($results, 'start_date'));
    }
)

Using collections, it would be a bit more readable.

$filtered = collect($date_ranges)
    ->filter(function ($item) use ($results) {
        return collect($results)->contains('start_date', $item);
    });
  • Related