Home > Net >  array_filter for string contained inside associative array
array_filter for string contained inside associative array

Time:10-07

I have an API that returns a HUGE array. I filter the returned data for the value "weekly" like this:

$results = array_filter($body['data'], function($item) {
        if(!isset($item['schedule']['type']))
            return false;
        return $item['schedule']['type'] == "weekly";
    });

The array $results looks like this:

Array
(
    [2] => Array
        (
            [title] => Title
            [description] => description
            [schedule] => Array (
                [type] => weekly
                [daily_time] => 16:00:00Z
                [weekdays] => Array
                    (
                        [0] => 1
                        [1] => 2
                        [2] => 3
                        [3] => 4
                        [4] => 5
                    )
            )
        [next_occurrence_time] => 2022-10-06T16:00:00 00:00
    )

    [3] => Array
        (
            [title] => Title 2
            [stream_title] => Title 2
            [stream_description] => description 2
            [schedule] => Array
            (
                [type] => weekly
                [start_time] => 
                [daily_time] => 16:00:00Z
                [scheduled_time] => 
                [weekdays] => Array
                    (
                        [0] => 2
                    )

            )
        [next_occurrence_time] => 2022-10-06T16:00:00 00:00
    )
    //More here...
)

The numbers represent a day of the week inside the [schedule][weekdays] array. I want to filter by specific day, so I can build a schedule. For example, I want to filter the $results array for and return every event on Tuesday.

My code only returns the data if Tuesday is the first [0] day in the array -> "Title 2". It does not return "Title" because Tuesday/2 is at the [1] position. How do I filter the associative array [schedule][weekday] and return any that contain "2"?

$filter = array("2");
$Tuesday = array_filter($results, function($e) use ($filter){
    return in_array($e['schedule']['weekdays'][0], $filter);
});
print_r($Tuesday);

changing to: return in_array($e['schedule']['weekdays'], $filter);

returns an empty array. I will need to do this for each day of the week and return the associated objects.

CodePudding user response:

Use array_intersect() to tell if there's any overlap between the weekdays array and $filter.

array_filter($results, function($e) use ($filter){
    return array_intersect($e['schedule']['weekdays'], $filter);
});

array_intersect() converts everything to strings before comparing, so it's OK if the datatypes are different in the JSON than $filter.

  • Related