php array_merge_recursive preserving numeric keys
Asked Answered
H

2

31

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 ()...

Hockett answered 21/8, 2012 at 9:19 Comment(0)
P
71

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',
//   ),
// )
Punish answered 21/8, 2012 at 9:36 Comment(2)
wait... merge = preserve conflicting keys; replace = merge conflicting keys?! That is why the world loves php...Policy
Thanks - but how ridiculous. This should have been implemented as an argument for array_merge_recursive().Ablebodied
I
0

Your expectation fails as the key of the $a and $b is numeric(!), even though you denoted it as a string literal (cf. PHP: Arrays -> Syntax).

I think whether or not there is a better solution depends on what you exactly need. It might be simpler than merging recursively:

1) Are you sure that every value inside the $a and $b arrays will always be an array again?

2) What is supposed to happen if these arrays share a common key (i.e. if "text" was again "up" in your example)? Keep merging recursively or not?

Impute answered 21/8, 2012 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.