views:

180

answers:

2

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

+3  A: 

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

Tatu Ulmanen
Indeed it works perfect, outputs what i need. Thank you. I am also sure that there is a ready made array function to use, i tried but could not get the result. Thank you again, i will use your code.
Dionysius
+1 just for codepad.org - I'd never seen it before. Pretty awesome.
Mailslut
+2  A: 

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.

Tom Haigh