简体   繁体   中英

how to merge 1d array into 2d array using PHP

i have 2 arrays with different dimensions, and how to merge my one dimension array to two dimension array, here is my 2 array look like

this is my two dimension array

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

and this is my one dimension array

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

this is what i expect from merging the arrays

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',
  ),

You need to merge the [0] element of the first array and the whole second array like this...

Code: ( Demo )

$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);

Output:

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',
  ),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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