比较两个关联数组,并创建匹配的数组新阵列,PHP [英] Compare two associative arrays and create a new array with the matched arrays, PHP

查看:162
本文介绍了比较两个关联数组,并创建匹配的数组新阵列,PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个数组:

  $ ARR1 =阵列(阵列(ID=→8,名= GT;测试1),
              阵列(ID=> 4,名= GT;测试2),
              阵列(ID=> 3,名= GT;TEST3)
           );$ ARR2 =阵列(阵列(ID=> 3)
              阵列(ID=→4)
           );

我怎样才能提取从$ ARR1,其中id在$ ARR2具有相同的值,数组到一个新的数组,离开提取的阵列也是一个新的数组,而没有考虑到关键的命令吗?

我要寻找的输出应该是:

  $ ARR3 =阵列(
              阵列(ID=→8,名= GT;测试1)
           );$ arr4 =阵列(阵列(ID=> 4,名= GT;测试2),
              阵列(ID=> 3,名= GT;TEST3)
           );

感谢


解决方案

我敢肯定有一个可以处理该些现成的魔法阵的功能,但这里有一个基本的例子:

  $ IDS =阵列();
的foreach($ ARR2作为编曲$){
    $编号[] = $改编['身份证'];
}$ ARR3 = $ arr4 =阵列();
的foreach($ ARR1作为编曲$){
    如果(in_array($改编['身份证'],$ IDS)){
        $ arr4 [] = $编曲;
    }其他{
        $ ARR3 [] = $编曲;
    }
}

的输出将是一样的,你想要的一个。活生生的例子:


  

    

HTTP://$c$cpad.org/c4hOdnIa


  

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

这篇关于比较两个关联数组,并创建匹配的数组新阵列,PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆