简体   繁体   中英

How to merge multiple two dimensional array based on first dimension key?

My problem statement is like follows: Suppose I have 2 two dimensional array. The arrays are:

$array1 = Array
(
[8] => Array
    (

        [branch_code] => DG-52484
        [total_desg] => 11

    )
);

$array2 = Array
(
[8] => Array
    (
        [total_dak] => 0
        [total_dak_decision] => 0

    )
);

After combining the two array my required out put will be:

Array
(
[8] => Array
    (

        [branch_code] => DG-52484
        [total_desg] => 11
        [total_dak] => 0
        [total_dak_decision] => 0


    )
);

Is there any php function for this type of task. Please note that i am not interested to use foreach or while in my situation.

Thanks in advance.

It will work with array_replace_recursive :

$array1 = Array(
    8 => Array(
        'branch_code' => 'DG-52484',
        'total_desg' => '11',
    )
);

$array2 = Array
(
    8 => Array(
        'total_dak' => 0,
        'total_dak_decision' => 0,
    )
);


var_dump(array_replace_recursive($array1, $array2));

Output

array (size=1)
  8 => 
    array (size=4)
      'branch_code' => string 'DG-52484' (length=8)
      'total_desg' => string '11' (length=2)
      'total_dak' => int 0
      'total_dak_decision' => int 0

try to use

$array = array(
    8 => array_merge($array1[8],$array2[8]);
);

You can use array_merge

$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);

Output

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

For more info http://php.net/manual/tr/function.array-merge.php

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