Tổng 2 mảng trong PHP

29 Jun 2020
0 Comments

arraySum.php

                
                    
<?php
/**
 * Function to sum two arrays
 *
 * @param array $a First array to merge
 * @param array $b Second array to merge which gonna be returned by function
 *
 * @return $b
 * @author Orlando Villegas Galán <orvigas@gmail.com>
 */
function sumArrays(array $a = [], array $b = [])
{
    foreach ($a as $k => $v) {//Iterate along the '$a' array, getting key value pair for every array position
        if (array_key_exists($k, $b)) {//Check if '$a' key exist in '$b'
            //If key exist into '$b' array
            if (is_array($v)) {//Check if value of key is an array
                //If value is an array
                $b[$k] = sumArrays($b[$k], $v);//The function is called itself recursively
            } else {
                //Otherwise
                $b[$k] += $v;//Accumulates the '$a' value in '$b' key position
            }
        } else {
            //Otherwise
            $b[$k] = $v; //Create key node in '$b'
        }
    }
    //Return merged '$b'
    return $b;
}

/** Array declaration **/
$a = [4, "a" => 3, "b" => ["ba" => 1, "bc" => 2], "c" => ["ca" => 4, "cb" => 3]];
$b = [5, "a" => 2, "b" => ["ba" => 4, "bc" => 3], "c" => ["ca" => 4]];

print_r(sumArrays($a, $b));

/** Output **/
/*
Array
(
    [0] => 9
    [a] => 5
    [b] => Array
        (
            [ba] => 5
            [bc] => 5
        )
    [c] => Array
        (
            [ca] => 8
            [cb] => 3
        )
)
*/
?>
                
            

Leave a Reply

This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.