Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array by its keys with another array [duplicate]

I have an array that looks like this:

Array
(
    [333824-00A-BLK-10] => Array
        (
            [classId] => 44
            [inv] => 0.000
            [onOrder] => 0
            [code] => 333824-00A-BLK-10
        )
    [333824-00A-BLK-10.5] => Array
        (
            [classId] => 44
            [inv] => 0.000
            [onOrder] => 0
            [code] => 333824-00A-BLK-10.5
        )
)

I want to use another array that looks like below to filter it with:

Array
(
    [0] => 333824-00A-BLK-10
    [1] => 333824-00A-BLK-10.5
    [2] => 333824-00A-BLK-11
    [3] => 333824-00A-BLK-11.5
    [4] => 333824-00A-BLK-12
)

I want to keep the results in the array and get rid of the keys that don't match. I have tried a function that filters the array with a foreach but no luck. Any help please? Thanks!

like image 917
Tyler Nichol Avatar asked Apr 29 '26 15:04

Tyler Nichol


1 Answers

$result = array_intersect_key($data, array_flip($keys));

Where $data is your main array, and $keys is an array with keys to filter

like image 151
zerkms Avatar answered May 02 '26 05:05

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!