Reputation: 13
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)
Upvotes: 0
Views: 59
Reputation: 1
Use array_filter
with third parameter ARRAY_FILTER_USE_KEY
to filter only keys.
array_filter($labels,
fn($label)=>in_array($label, $get_options),
ARRAY_FILTER_USE_KEY);
Upvotes: 0
Reputation: 12949
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));
Upvotes: 2