简体   繁体   中英

How to merge or push or add new key and values to existing array

The array is like this

Array 1
(
    [2014-07-01] => Array
        (
            [date] => 2014-07-01
            [totalr] => 13
        )

    [2014-07-02] => Array
        (
            [date] => 2014-07-02
            [totalr] => 18
        )
   //... one for each day of the month
)

An then I have another array very similar to the one before the only key that changes is the key "total"

Array 2
(
    [2014-07-01] => Array
        (
            [date] => 2014-07-01
            [members] => 21
        )

    [2014-07-02] => Array
        (
            [date] => 2014-07-02
            [members] => 30
        )
   //... one for each day of the month
)

So with both arrays I need to build a single array, so the final array need to be like this:

Final Array
(
    [2014-07-01] => Array
        (
            [date] => 2014-07-01
            [totalr] => 13
            [members] => 21
        )

    [2014-07-02] => Array
        (
            [date] => 2014-07-02
            [totalr] => 18
            [members] => 30
        )
// One for each day of the month
)

the key for each block is the same for each array... I already try array_merge didn't work... so how do I do that?...

UPDATE - 8-13-2014 08:12
Based on @ChicagoRedSox comment I find this function:

    function juntaArrs($arr1, $arr2) {
        if (!is_array($arr1) or !is_array($arr2)) { return $arr2; }
        foreach ($arr2 AS $sKey2 => $sValue2) {
            $arr1[$sKey2] = juntaArrs(@$arr1[$sKey2], $sValue2);
        }
        return $arr1;
    }
  $new_arr = juntaArrs($a1, $a2);
  print_r($new_arr);

it works perfectly!! thank you.

// start with a new array
$newArr = array();
// for every key and value in array 1
foreach($arr1 as $k=>$v){
    // add in the new array at key each key an array with date (the key),
    // totalr (the second value in the sub-array) and numbers (the second value in
    // the array 2 at the key position
    $newArr[$k] = array('date'=>$k, 'totalr'=>$v[1], 'numbers'=>$arr2[$k][1]);
}
// it's what we obtain
print_r($newArr);

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