php array_merge_recursive preserving numeric keys

user1125394 picture user1125394 · Aug 21, 2012 · Viewed 14.5k times · Source

I would simply like to merge

$a = array("59745506"=>array("up" => 0,));
$b = array("59745506"=>array("text" => "jfrj"));
$c = array_merge_recursive_new($a, $b);

result:

Array
(
    [0] => Array
        (
            [up] => 0
        )

    [1] => Array
        (
            [text] => jfrj
        )

)

expected result:

    Array
(
    [59745506] => Array
        (
            [up] => 0
            [text] => jfrj
        )

)

the 2nd comment in http://www.php.net/manual/en/function.array-merge-recursive.php is working, is it the best solution for my case (where I need to merge arrays with multiple numeric keys, and with 2 levels)?

another workaround would be to implement it with array_map(function ()...

Answer

salathe picture salathe · Aug 21, 2012

The array_replace_recursive() function looks to be what you need.

$a = array("59745506" => array("up" => 0,));
$b = array("59745506" => array("text" => "jfrj"));
$c = array_replace_recursive($a, $b);
var_export($c);

// array (
//   59745506 => 
//   array (
//     'up' => 0,
//     'text' => 'jfrj',
//   ),
// )