Home > Software engineering >  how to get all elements of array that have ids that are in another array
how to get all elements of array that have ids that are in another array

Time:12-19

suppose that I have an array. each element is another array which has "id", "name", "age" etc. keys.

$students = array(
    array(
        "id"=>1,
        "name"=>"Alice",
        "age"=>22
    ),
    array(
        "id"=>3,
        "name"=>"Bob",
        "age"=>22
    )
    ,array(
        "id"=>4,
        "name"=>"carol",
        "age"=>22
    )
);

now I have another array containing some IDs ,$ids = array(1,4); how do I get the elements in first array that have ids that are in the second array.

expected result:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Alice
        [age] => 22
    )

[2] => Array
    (
        [id] => 4
        [name] => carol
        [age] => 22
    )

)

what about the case in which the first array is an array of objects instead of array of arrays?

I tried array_intersect and array_intersect_key but they are not built for this purpose. should I use array_map?

CodePudding user response:

As per the suggestion made above by @CBroe, you can solve the filtering of the source array like this.

$students = array(
    array(
        "id"=>1,
        "name"=>"Alice",
        "age"=>22
    ),
    array(
        "id"=>3,
        "name"=>"Bob",
        "age"=>22
    )
    ,array(
        "id"=>4,
        "name"=>"carol",
        "age"=>22
    )
);

$ids=array(1,4);

/*
    Array filter with an anonymouse callback that 
    `uses` the IDs array ( could use a global )
    and performs a simple `in_array` test - returning
    that value if true.
*/
$result=array_filter( $students, function( $item ) use( $ids ){
    return in_array( $item['id'], $ids );
});


printf('<pre>%s</pre>',print_r($result,true));

which yields the desired output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [age] => 22
        )

    [2] => Array
        (
            [id] => 4
            [name] => carol
            [age] => 22
        )

)
  • Related