Search code examples
phparraysintersect

Intersect One and Two-Dimensional Arrays


I have an array that has labels assigned to keys and an array that has those keys. I need to intersect those two arrays by single dimensional value and multidimensional key. Is there a single php function that allows this? I've read through the php array functions but couldnt really find something that fits.

$labels = array( 
    '7d' => __( 'Wöchentlich', 'aboprodukt' ),
    '14d' => __( 'Alle zwei Wochen', 'aboprodukt' ),
    '1m' => __( 'Monatlich', 'aboprodukt' ),
    '2m' => __( 'Alle zwei Monate', 'aboprodukt' ) );

$get_options = array( '7d','14d','1m');

this should result in:

$result = array(
    '7d' => __( 'Wöchentlich', 'aboprodukt' ),
    '14d' => __( 'Alle zwei Wochen', 'aboprodukt' ),
    '1m' => __( 'Monatlich', 'aboprodukt' ) );

(without the '2m' key->value-pair)


Solution

  • Something like this:

    $result = array_filter($labels, 
        function($k) use($get_options) {
            return in_array($k, $get_options);
        },
        ARRAY_FILTER_USE_KEY
    );
    

    but you could also do something like this:

    array_intersect_key($labels, array_flip($get_options));