3

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!

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Tyler Nichol
  • 635
  • 2
  • 7
  • 28
  • [Filter array by its key using the values of another array and order results by second array](https://stackoverflow.com/q/11265133/2943403) – mickmackusa Oct 21 '22 at 15:13

2 Answers2

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

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

zerkms
  • 249,484
  • 69
  • 436
  • 539
0

I would make a dummy array and filter it in a foreach, i dont know how you foreach looked but mine would look like

$arr = array();

$filter_array = array ('333824-00A-BLK-10',
     '333824-00A-BLK-10.5',
     '333824-00A-BLK-11',
    '333824-00A-BLK-11.5',
     '333824-00A-BLK-12');

$array_to_filter = 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'
        )
);

foreach($array_to_filter as $filter) {

    if(array_key_exists($filter, $array_to_filter)) {
        $arr[] = $array_to_filter[$filter];
    }
}

in $arr you should now have all the existing keys in your array

Soundz
  • 1,308
  • 10
  • 17