php二位数组合并

时间:2023-12-15 12:01:50

转自:http://www.cnblogs.com/losesea/archive/2013/06/14/3134900.html

题目:有以下2个二维数组

1
$a=Array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux ));
2
$b=Array(0 => Array(class_count=> 8),1 => Array(class_count => 2));
两个数组内容如上,如何把$a和$b合并成为一个新的二维数组,要求新数组内容如下:

1
Array(0 => Array(id => 66,class_name => www.iiwnet.com,class_count=> 8),1 => Array(id => 67,class_name => linux ,class_count => 2));
这个题目一定有人遇到过 正好今天群里有人问 就给出2种解法
以下代码由 PHP教程网 原创提供
01
方法一:
02
 
03
    function arrpreg(){
04
        $a=Array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux ));
05
        $b=Array(0 => Array(class_count=> 8),1 => Array(class_count => 2));
06
        $arr = array();
07
        foreach ($a as $k => $r) {
08
            foreach($r as $k1 => $r1){
09
                $arr[$k][$k1] = $r1;
10
            }
11
        }  
12
        foreach ($b as $k => $r) {
13
            foreach($r as $k1 => $r1){
14
                $arr[$k][$k1] = $r1;
15
            }
16
        }
17
        return $arr;
18
    }
19
    $ar= arrpreg();  
20
    echo '<pre>';
21
     print_r($ar);
22
    echo '</pre>';
23
    ?>
24
 
25
方法二:
26
 
27
    $a = array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux ));
28
    $b = array(0 => Array(class_count=> 8),1 => Array(class_count => 2));
29
    $arr = array();
30
    foreach($a as $k=>$r){
31
        $arr[] = array_merge($r,$b[$k]);
32
    }
33
    echo '<pre>';
34
    print_r($arr);
35
    echo '</pre>';

转自http://www.2cto.com/kf/201210/159324.html

PHP二维数组合并,根据某个key合并

最终解决方案:

  1. /**
  2. *
  3. * @param type $v 要传入的组合阵列
  4. * @param type $keyname 对应的KEY名称。
  5. * @param type $valname 要写入的值KEY名称
  6. * @param type $s 重组译的阵例。预设空值。
  7. */
  8. function test($v,$keyname,$valname,$s=Array())
  9. {
  10. foreach($v AS $_k => $d)
  11. {
  12. $s[$d[$keyname]][$valname]= $d[$valname];
  13. }
  14. return $s;
  15. }
  16. $key ='server_id';
  17. foreach($arr1 as $k=>$v){
  18. $arr[$v['server_id']]= $v;
  19. }
  20. $data = test($arr2,$key,'arr2',$arr);
  21. $data = test($arr3,$key,'arr3',$data);

转自http://www.dewen.org/q/7551