0

How I merge two array including the keys, below array structure available with requirement, can any one help for this:

$a1=array('533532'=>array('token'=>'token','tripboardrefid'=>'tripboardrefid'));

$a2=array('533179'=>array('token'=>'token','tripboardrefid'=>'tripboardrefid'));

print_r(array_merge($a1,$a2));

Getting this structure:

Array
(
    [0] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
        )

    [1] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
        )

)

Need this structure:

Array
(
    [533179] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
        )
    [533532] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
            
        )

)
shaedrich
  • 5,457
  • 3
  • 26
  • 42
  • Does this answer your question? [PHP: merge two arrays while keeping keys instead of reindexing?](https://stackoverflow.com/questions/3292044/php-merge-two-arrays-while-keeping-keys-instead-of-reindexing) – Andrea Olivato Mar 14 '22 at 16:38

2 Answers2

0

Use + notation to get the merged state with preserved keys.

print_r($a1 + $a2);

will print

Array
(
    [533532] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
        )

    [533179] => Array
        (
            [token] => token
            [tripboardrefid] => tripboardrefid
        )

)
Ersin
  • 124
  • 3
0

You can use array_replace() function:

array_replace($a1, $a2);
Dori Rina
  • 364
  • 2
  • 7