phparraysfilterwhitelistarray-intersect

Filter an array by keeping elements with a key found in a whitelist array


I have an multidimensional array like this, but I just only need some index to be displayed.

Array

    Array
    (
        [0] => Array
            (
                [1] => 220
                [38] => 200
                [232] => 970
            )
    
        [1] => Array
            (
                [0] => 220
                [2] => 190
                [39] => 200
            )
    
        [2] => Array
            (
                [1] => 190
                [3] => 40
                [50] => 220
            )
    
        [3] => Array
            (
                [2] => 40
                [4] => 200
                [57] => 120
            )
    )

then i just want to display only index [1] and [3], so it would be like this

Array
(
    [1] => Array
        (
            [0] => 220
            [2] => 190
            [39] => 200
        )


    [3] => Array
        (
            [2] => 40
            [4] => 200
            [57] => 120
        )
)

i try using this code

$order = array(1,3);

uksort($graph, function($key1, $key2) use ($order) {
    return (array_search($key1, $order) > array_search($key2, $order));
});

but still, it's displayed the rest array that I don't need ([0] and [2]).


Solution

  • Like this:

    foreach(array_keys($graph) as $key) 
    {    
        if($key == 0|| $key == 2)
        {
            unset($graph[$key]);
        }
    }
    

    print_r

    Array
    (
        [1] => Array
            (
                [0] => 220
                [2] => 190
                [39] => 200
            )
    
        [3] => Array
            (
                [2] => 40
                [4] => 200
                [57] => 120
            )
    
    )