Search code examples
phparraysmergearray-merge

Merge array with same keys, array_merge_recursive doesn't work as expected


I've two arrays with ids as key and some fields and I would like to merge them but I don't understand why it doesn't work, here is my example code:

$Podcasts1 = array("1234" => array('title' => "myTitle", "type" => "myType"));
$Podcast2 = array("1234" => array("content" => "myContent"));
$podcasts = array_merge_recursive($Podcasts1, $Podcast2);
var_dump($Podcasts1, $Podcast2, $podcasts);

There is the result:

array:1 [▼
  1234 => array:2 [▼
    "title" => "myTitle"
    "type" => "myType"
  ]
]
array:1 [▼
  1234 => array:1 [▼
    "content" => "myContent"
  ]
]
array:2 [▼
  0 => array:2 [▼
    "title" => "myTitle"
    "type" => "myType"
  ]
  1 => array:1 [▼
    "content" => "myContent"
  ]
]

And there is the result I woulk like to have:

array:[
1234 => array(
        "title" => "myTitle"
        "type" => "myType"
        "content" => "myContent")
]

I don't understand why the code given on PHP.net work and mine doesn't

Code:

$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);

Result:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

Solution

  • Change the key 1234 to string like

     $Podcasts1 = array('a' => array('title' => "myTitle", "type" => "myType"));
     $Podcast2 = array('a' => array("content" => "myContent"));
     $podcasts = array_merge_recursive($Podcasts1, $Podcast2);
     var_dump($Podcasts1, $Podcast2, $podcasts);
    

    array_merge_recursive works on string keys.