简体   繁体   中英

How to merge array key in php

array (size=1)
  11 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Maths' => string '21' (length=2)

array (size=1)
  10 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Maths' => string '10' (length=2)

array (size=1)
  11 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Gujarati' => string '21' (length=2)

array (size=1)
  10 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Gujarati' => string '20' (length=2)

array key duplicate like 11 and 10

MY Question: How to Create Below output array .

array (size=1)
  11 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Maths' => string '21' (length=2)
         'Gujarati' => string '21' (length=2)

array (size=1)
  10 => 
    array (size=1)
      'subject' => 
        array (size=1)
          'Maths' => string '10' (length=2)
         'Gujarati' => string '20' (length=2)

Use this function to get your result. Btw: Just asking for help again and again without investigating by yourself is bad behavior, if someone points you to a function (like array_merge_recursive) you should at least take some time to RTM.

function array_merge_recursive_new() {

    $arrays = func_get_args();
    $base = array_shift($arrays);

    foreach ($arrays as $array) {
        reset($base); //important
        while (list($key, $value) = @each($array)) {
            if (is_array($value) && @is_array($base[$key])) {
                $base[$key] = array_merge_recursive_new($base[$key], $value);
            } else {
                $base[$key] = $value;
            }
        }
    }

    return $base;
}

Source/Copyright: http://php.net/manual/en/function.array-merge-recursive.php#106985

I have tested it with these arrays, which should be the same as you have them.

$arr1 = array(
    10 => array( "subject" => array("math" => 1)),
    11 => array( "subject" => array("math" => 2)),
);

$arr2 = array(
    10 => array( "subject" => array("guawhatever" => "foo")),
    11 => array( "subject" => array("guawhatever" => "bar")),
);
$blubb = array_merge_recursive_new($arr1,$arr2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM