比较两个关联数组并使用匹配的数组PHP创建一个新数组

时间:2021-07-20 12:48:15

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?

我如何从$ arr1“提取”数组,其中id在$ arr2中具有相同的值,进入一个新数组并将提取的数组保留在一个新数组中,而不考虑关键命令?

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

谢谢

2 个解决方案

#1


6  

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

http://codepad.org/c4hOdnIa

#2


3  

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

您可以将array_udiff()和array_uintersect()与自定义比较函数一起使用。

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.

我想这可能最终比其他答案慢,因为这将超过数组两次。

#1


6  

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

http://codepad.org/c4hOdnIa

#2


3  

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

您可以将array_udiff()和array_uintersect()与自定义比较函数一起使用。

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.

我想这可能最终比其他答案慢,因为这将超过数组两次。