简体   繁体   English

如何合并或推送或向现有数组添加新键和值

[英]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" 然后我有另一个数组,该数组与之前唯一更改的唯一键为“ 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?... 每个模块的每个块的键都相同...我已经尝试了array_merge不起作用...所以我该怎么做?

UPDATE - 8-13-2014 08:12 更新-8-13-2014 08:12
Based on @ChicagoRedSox comment I find this function: 基于@ChicagoRedSox注释,我发现此功能:

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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