当前位置:Gxlcms > PHP教程 > 关于数组合并的有关问题

关于数组合并的有关问题

时间:2021-07-01 10:21:17 帮助过:16人阅读

关于数组合并的问题
原数组:

$args1 = Array(
'0' => array(
'0' => 'a',
'1' => array(
'0' => array ( 'col1' => 'A1', 'col2' => 0 )
)
),
'1' => array(
'0' => 'b',
'1' => array(
'0' => array ( 'col1' => 'B1', 'col2' => 1 )
)
)
);
$args2 = Array(
'0' => array(
'0' => 'a',
'1' => array(
'0' => Array ( 'col1' => 'A2', 'col2' => 0 ),
'1' => Array ( 'col1' => 'A3', 'col2' => 0 )
)
)
);


目标数组:

Array(
'0' => array(
'0' => 'a',
'1' => array(
'0' => array ( 'col1' => 'A1', 'col2' => 0 ),
'1' => Array ( 'col1' => 'A2', 'col2' => 0 ),
'2' => Array ( 'col1' => 'A3', 'col2' => 0 )
)
),
'1' => array(
'0' => 'b',
'1' => array(
'0' => array ( 'col1' => 'B1', 'col2' => 1 )
)
)
);


------解决方案--------------------
$res = array();
foreach($args1 as $item) $res[$item[0]] = $item;
foreach($args2 as $item) $res[$item[0]][1] = array_merge($res[$item[0]][1], $item[1]);

print_r(array_values($res));
Array
(
[0] => Array
(
[0] => a
[1] => Array
(
[0] => Array
(
[col1] => A1
[col2] => 0
)

[1] => Array
(

人气教程排行