Search code examples
phparraysfilteringrelationalassociative

How to associate and filter two related arrays?


I have two arrays and I want to link together when processing them.

$dat = array(
    "2020-02-01", 
    "2020-02-05",
    "2020-02-10",
    "2020-02-12",
    "2020-02-15"
);
$word = array(
    "Attend To,Explore,Unaided,dull,bad"
); 

//User input
$start = "2020-01-01";
$end = "2020-02-07";

I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.

//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
    return $data_item >= $start && $data_item <= $end;
});

and the result is

Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)

I want it to be able to link $dat and $word so that the result for word too will be

Array
(
    [0] => Attend To
    [1] => Explore
)

Solution

  • The original keys will be maintained after array_filter, so get the entries for keys that are the same by computing the intersection. It appears that $word is a one element array with a string, so just explode it:

    $word_result = array_intersect_key(explode(',', $word[0]), $result);
    

    See a Demo.

    If one of the arrays has unique values, you can combine the array and just operate on that.

    $comb = array_combine(explode(',', $word[0]), $dat);
    
    $result = array_filter($comb, function($data_item) use($start,$end) {
        return $data_item >= $start && $data_item <= $end;
    });
    

    This yields:

    Array
    (
        [Attend To] => 2020-02-01
        [Explore] => 2020-02-05
    )
    

    You can use the array as is or use array_keys to get the keys as the $word array.

    If it's not guaranteed to be $word[0] then you can use reset($word) or current($word).