PHP把2个二维数组合并一个二维数组2种解法

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

$a=Array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux )); 
$b=Array(0 => Array(class_count=> 8),1 => Array(class_count => 2)); 

两个数组内容如上,如何把$a和$b合并成为一个新的二维数组,要求新数组内容如下:

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教程网 原创提供

方法一:

    function arrpreg(){
        $a=Array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux ));
        $b=Array(0 => Array(class_count=> 8),1 => Array(class_count => 2));
        $arr = array();
        foreach ($a as $k => $r) {
            foreach($r as $k1 => $r1){
                $arr[$k][$k1] = $r1;
            }
        }    
        foreach ($b as $k => $r) {
            foreach($r as $k1 => $r1){
                $arr[$k][$k1] = $r1;
            }
        }
        return $arr;
    }
    $ar= arrpreg();    
    echo '<pre>';
     print_r($ar);
    echo '</pre>';
    ?>

方法二:

    $a = array(0 => Array(id => 66,class_name => www.iiwnet.com),1 => Array(id => 67,class_name => linux ));
    $b = array(0 => Array(class_count=> 8),1 => Array(class_count => 2));
    $arr = array();
    foreach($a as $k=>$r){
        $arr[] = array_merge($r,$b[$k]);
    }
    echo '<pre>';
    print_r($arr);
    echo '</pre>';


 

你可能感兴趣的:(php教程,php数组合并)