簡體   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