0

I have two array that is

$a = array( 
    array(
        'id' => 1,
        'name' => "Facebook" 
    ),
    array(
        'id' => 2,
        'name' => "Twitter" 
    ),
    array(
        'id' => 3,
        'name' => "Google" 
    ),
    array(
        'id' => 4,
        'name' => "Linkdin" 
    ),
    array(
        'id' => 5,
        'name' => "Github" 
    ),
);

And another is,

$b = array(1, 3, 5);

According to the $b array value, $a associative array id will be selected as result. intersect two array So the result will be,

$result = $a = array( 
    array(
        'id' => 1,
        'name' => "Facebook" 
    ),
    array(
        'id' => 3,
        'name' => "Google" 
    ),
    array(
        'id' => 5,
        'name' => "Github" 
    ),
);
Optimus Prime
  • 308
  • 6
  • 22

3 Answers3

1

Simple oneliner (more readable with 4 lines though):

$result = array_filter(
    $a, 
    function($v) use ($b) { return in_array($v['id'], $b); }
);
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1
foreach ($a as $key => $value) {
    if (in_array($value['id'], $b)) {
        $result[] = $value;
    }
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
hak
  • 48
  • 5
1

Another way computing the intersection:

$result = array_intersect_key(array_column($a, null, 'id'), array_flip($b));
  • Reindex $a by id
  • Flip $b to get values as keys
  • Compute the intersection of the keys
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87