Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have this 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 have 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 output i am looking for should be:

$arr3=array(
              array("id" => 8, "name" => "test1")
           );

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

Thanks

like image 846
dciccale Avatar asked May 21 '10 12:05

dciccale


People also ask

How do you find the difference between two associative arrays in PHP?

The array_diff_assoc() function compares the keys and values of two (or more) arrays, and returns the differences. This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

How can I find matching values in two arrays PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

Which PHP function returns an array with the elements of two or more arrays in one array?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

Which PHP functions compare arrays and return the differences?

The array_diff() function compares the values of two (or more) arrays, and returns the differences.


2 Answers

I'm sure there's some ready made magical array functions that can handle this, but here's 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 desired. Live example:

http://codepad.org/c4hOdnIa

like image 116
Tatu Ulmanen Avatar answered Oct 18 '22 11:10

Tatu Ulmanen


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 end up being slower than the other answer, as this will be going over the arrays twice.

like image 30
Tom Haigh Avatar answered Oct 18 '22 09:10

Tom Haigh