Pietro Speroni
Pietro Speroni

Reputation: 3221

How to efficiently extract a sub array based upon a set of keys

I have an array of arrays $data.

With

print_r($data); 

returning

Array ( 
[1401] => Array ( [0] => 94 [1] => 2 [2] => 159 ) 
[1402] => Array ( [0] => 94 [1] => 2 [2] => 50 [3] => 23 [4] => 159 ) 
[1403] => Array ( [0] => 94 [1] => 2 [2] => 50 ) 
[1404] => Array ( [0] => 94 [1] => 90 [2] => 50 [3] => 23 ) 
[1405] => Array ( [0] => 94 [1] => 90 ) 
[1406] => Array ( [0] => 94 [1] => 90 [2] => 23 ) 
[1407] => Array ( [0] => 94 [1] => 90 [2] => 50 )
) 

The keys are a set of numbers. And I need to extract from this array a sub array which has only the keys stored in another variable.

$toextract=array(1402,1406);

Apart building one by one the new array with a loop, is there a simpler way. I will need to run this command multiple times so it is quite important that is fast.

Upvotes: 1

Views: 328

Answers (1)

KingCrunch
KingCrunch

Reputation: 131891

 $result = array_intersect_key($data, array_flip(array(1402, 1406));

array_intersect_key()

Upvotes: 6

Related Questions