简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM