php array_merge_recursive preserving numeric keys

前端 未结 2 1276
一个人的身影
一个人的身影 2020-12-29 04:07

I would simply like to merge

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


        
相关标签:
2条回答
  • 2020-12-29 04:37

    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',
    //   ),
    // )
    
    0 讨论(0)
  • 2020-12-29 04:51

    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?

    0 讨论(0)
提交回复
热议问题