8, "name" ...">

Compare two associative arrays and create a new array with the corresponding arrays, PHP

I have two arrays:

$arr1=array( array("id" => 8, "name" => "test1"), array("id" => 4, "name" => "test2"), array("id" => 3, "name" => "test3") ); $arr2=array( array("id" => 3), array("id" => 4) ); 

How can I “extract” arrays from $ arr1, where id has the same value in $ arr2, into a new array and leave the extracted array also in a new array without taking into account key orders?

The result I'm looking for should be:

 $arr3=array( array("id" => 8, "name" => "test1") ); $arr4=array( array("id" => 4, "name" => "test2"), array("id" => 3, "name" => "test3") ); 

thanks

+7
arrays php associative-array extract compare
source share
2 answers

I'm sure there are some ready-made magic array functions that can handle this, but here is a basic example:

 $ids = array(); foreach($arr2 as $arr) { $ids[] = $arr['id']; } $arr3 = $arr4 = array(); foreach($arr1 as $arr) { if(in_array($arr['id'], $ids)) { $arr4[] = $arr; } else { $arr3[] = $arr; } } 

The output will be the same as the one you need. Real-time example:

http://codepad.org/c4hOdnIa

+6
source share

You can use array_udiff() and array_uintersect() with a custom comparison function.

 function cmp($a, $b) { return $a['id'] - $b['id']; } $arr3 = array_udiff($arr1, $arr2, 'cmp'); $arr4 = array_uintersect($arr1, $arr2, 'cmp'); 

I guess this may turn out to be slower than the other answer, as this will go through the arrays twice.

+3
source share

All Articles