PHP数组合并

数组A

array(3) {
  [0] => array(1) {
    ["account"] => string(1) "6"
  }
  [1] => array(1) {
    ["account"] => string(1) "3"
  }
}

数组B

array(2) {
  [0] => array(1) {
    ["netfile"] => string(1) "7"

  }
  [1] => array(1) {
    ["netfile"] => string(1) "2"
  }
}

数组C

array(2) {
  [0] => array(1) {
    ["cf"] => string(1) "9"

  }
  [1] => array(1) {
    ["cf"] => string(1) "2"
  }
}

如何把这三个数组合并成

 array(4) {
  [0] => array(3) {
    ["netfile"] => string(1) "9"
    ["account"] => string(1) "6"
    ["cf"] => string(1) "9"

  }
  [1] => array(3) {
    ["netfile"] => string(1) "2"
    ["account"] => string(1) "3"
    ["cf"] => string(1) "2"
  }

求大神指导 感谢^^

阅读 3k
3 个回答
function mergeArr($a,$b,$c) {
        return array_merge($a,$b,$c);
}

$a = ['0'=>['account' => '6'],'1'=>['account' => '3']];
$b = ['0'=>['netfile' => '7'],'1'=>['netfile' => '2']];
$c = ['0'=>['cf' => '9'],'1'=>['cf' => '2']];
var_dump(array_map('mergeArr', $a,$b,$c));

输出:

array:2 [▼
  0 => array:3 [▼
    "account" => "6"
    "netfile" => "7"
    "cf" => "9"
  ]
  1 => array:3 [▼
    "account" => "3"
    "netfile" => "2"
    "cf" => "2"
  ]
]
/**
 * 合并通过数据库查出来的数据集,比如$a = array(0=>array('f1'=>'v1','f2'=>'v2'));$b = array(0=>array('f3'=>'v3','f4'=>'v4'));
 *
 * @param array $a 数据集1
 * @param array $b 数据集2
 * @return array 返回如:$c = array(0=>array('f1'=>'v1','f2'=>'v2','f3'=>'v3','f4'=>'v4'));
 */
function dataset_merge(array $a,array $b) //合并数据集
{
    $d = array();
    foreach($a as $k => $v) {
        if (array_key_exists($k,$b))
            $d[$k] = array_merge((array)$v,(array)$b[$k]);
        else
            $d[$k] = $v;
    }
    foreach($b as $k => $v) {
        if (!array_key_exists($k,$d)) {
            $d[$k] = $v;
        }
    }
    return $d;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏