php,合并数组,合并一维数组,合并二维数组,合并多维数组
合并数组 例子1: <?php $msg = [ "code" => "0", "msg" => "", "count" => "", ]; $data = [ "name" => "lady", "age" => "0", "count" => "0", ]; $msg['data'] = $data; print_r($msg); 输出: Array ( [code] => 0 [msg] => [count] => [data] => Array ( [name] => lady [age] => 0 [count] => 0 ) ) 例子二: <?php $a1 = [ 'red', 'green', ]; $a2 = [ 'blue', 'yellow', ]; print_r(array_merge($a1, $a2)); 输出: Array ( [0] => red [1] => green [2] => blue [3] => yellow ) 例子三: <?php $a1 = [ 'apple' => 'red', 'banner' => 'yellow', ]; $a2 = [ 'pear' => 'yellwo', 'apple' => 'green', ]; $result = array_merge_recursive($a1, $a2); print_r($result); 输出: Array ( [apple] => Array ( [0] => red [1] => green ) [banner] => yellow [pear] => yellwo ) 例子四: <?php $a = array('color' => 'red'); $b = array('color' => 'blue', 'type' => 'fruit'); $arr = $a + $b; print_r($arr); 输出: Array ( [color] => red [type] => fruit ) 例子五: <?php $a = [ [ 'id' => '1', 'name' => '张三', 'age' => '18', ], [ 'id' => '1', 'name' => '小米', 'age' => '15', ], [ 'id' => '3', 'name' => '张三', 'age' => '20', ], [ 'id' => '3', 'name' => '张六', 'age' => '29', ], [ 'id' => '3', 'name' => '张三疯', 'age' => '20', ], ]; $b = []; foreach ($a as $k => $v) { if (!isset($b[$v['id']])) { $b[$v['id']] = $v; } else { $b[$v['id']]['name'] .= ',' . $v['name']; } } // echo '<pre>'; print_r(array_values($b)); 输出: Array ( [0] => Array ( [id] => 1 [name] => 张三,小米 [age] => 18 ) [1] => Array ( [id] => 3 [name] => 张三,张六,张三疯 [age] => 20 ) ) 例子六: <?php $arr = array( array( 'id' => 1, 'pid' => 0, 'name' => '新闻分类', ), array( 'id' => 2, 'pid' => 0, 'name' => '最新公告', ), array( 'id' => 3, 'pid' => 1, 'name' => '国内新闻', ), array( 'id' => 4, 'pid' => 1, 'name' => '国际新闻', ), array( 'id' => 5, 'pid' => 0, 'name' => '图片分类', ), array( 'id' => 6, 'pid' => 5, 'name' => '新闻图片', ), array( 'id' => 7, 'pid' => 5, 'name' => '其它图片', ), ); //整理函数 /** * 生成无限级树算法 * @author Baiyu 2014-04-01 * @param array $arr 输入数组 * @param number $pid 根级的pid * @param string $column_name 列名,id|pid父id的名字|children子数组的键名 * @return array $ret */ function make_tree($arr, $pid = 0, $column_name = 'id|pid|children') { list($idname, $pidname, $cldname) = explode('|', $column_name); $ret = array(); foreach ($arr as $k => $v) { if ($v[$pidname] == $pid) { $tmp = $arr[$k]; unset($arr[$k]); $tmp[$cldname] = make_tree($arr, $v[$idname], $column_name); $ret[] = $tmp; } } return $ret; } $output_array = make_tree($arr); print_r($output_array); 输出: Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 新闻分类 [children] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 国内新闻 [children] => Array ( ) ) [1] => Array ( [id] => 4 [pid] => 1 [name] => 国际新闻 [children] => Array ( ) ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 最新公告 [children] => Array ( ) ) [2] => Array ( [id] => 5 [pid] => 0 [name] => 图片分类 [children] => Array ( [0] => Array ( [id] => 6 [pid] => 5 [name] => 新闻图片 [children] => Array ( ) ) [1] => Array ( [id] => 7 [pid] => 5 [name] => 其它图片 [children] => Array ( ) ) ) ) )