繁体   English   中英

如何使用PHP将一维数组合并为二维数组

[英]how to merge 1d array into 2d array using PHP

我有2个具有不同维度的数组,以及如何将我的一维数组合并为二维数组,这是我的2个数组的样子

这是我的二维数组

array (
0 => 
array (
'id' => 1,
'alias' => 'Anderson',
'location' => 'Semarang',
    'up' => 39144,
'status' => 'DOWN',
),

这是我的一维数组

 array (
  'last_accessed_by' => 1,
  'last_refresh' => '2018-10-29 00:21:39',
   'created_at' => '2018-10-29 00:21:39',
 )

这是我从合并数组中获得的期望

array (
  0 => 
  array (
    'id' => 1,
    'alias' => 'Anderson',
    'location' => 'Semarang',
    'up' => 39144,
    'status' => 'DOWN',
    'last_accessed_by' => 1,
    'last_refresh' => '2018-10-29 00:21:39',
    'created_at' => '2018-10-29 00:21:39',
  ),

您需要像这样合并第一个数组的[0]元素和整个第二个数组的元素...

代码:( 演示

$array1 = array (
    array (
        'id' => 1,
        'alias' => 'Anderson',
        'location' => 'Semarang',
        'up' => 39144,
        'status' => 'DOWN'
    )
);

$array2 =  array (
    'last_accessed_by' => 1,
    'last_refresh' => '2018-10-29 00:21:39',
    'created_at' => '2018-10-29 00:21:39'
);
$array1[0] = array_merge($array1[0], $array2);
// or because merging associative arrays, if you aren't scared of array union operators:
// $array1[0] += $array2;
//            ^^-- this merges the 2nd to [0] of the 1st without a function call

var_export($array1);

输出:

array (
  0 => 
  array (
    'id' => 1,
    'alias' => 'Anderson',
    'location' => 'Semarang',
    'up' => 39144,
    'status' => 'DOWN',
    'last_accessed_by' => 1,
    'last_refresh' => '2018-10-29 00:21:39',
    'created_at' => '2018-10-29 00:21:39',
  ),
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM