将具有相同第一个键值的数组添加到一起

时间:2014-07-17 04:24:31

标签: php arrays

我在这样的数组中有这个简单的数组,有N个嵌套数组

[  
   {  
      "period":"2014-07-16",
      "test":1
   },
   {  
      "period":"2014-07-15",
      "test2":1
   },
   {  
      "period":"2014-07-16",
      "test2":47
   }
]

我一直在努力(使用许多不同且同样失败的方法)合并具有相同周期的那些并且如果它们具有相同的第二个键(在这种情况下为test2),则将它们一起添加。如果没有,则将该键添加到数组中。

[
   {
      "period":"2014-07-16",
      "test":1,
      "test2":48
   },
   {
      "period":"2014-07-15",
      "test2":1  
   },

]

我最近的尝试是最接近我想要的(下面的代码)

        // $datesArray is the first mentioned array of values.
        // finalArray is an empty array that I want to push the final values into.
        for ($i = 0; $i < count($datesArray) - 1; $i++) { 

            for ($j = $i; $j < count($datesArray); $j++) { 

                $key1 = array_keys($datesArray[$i]);
                $key2 = array_keys($datesArray[$j]);
                // First check to see if they have the same date, if they don't then no merging!
                if ($datesArray[$i]['period'] == $datesArray[$j]['period']) {
                    if ($j == $i) {
                        array_push($finalArray, array(
                            'period' => $datesArray[$i]['period'],
                            $key1[1] => $datesArray[$i][$key1[1]]
                        ));
                    } else {
                        if ($key1[1] == $key2[1]) {
                            array_push($finalArray, array(
                                'period' => $datesArray[$i]['period'], 
                                $key1[1] => $datesArray[$i][$key1[1]] + $datesArray[$j][$key2[1]]
                            ));
                        } else {
                            array_push($finalArray, array(
                                'period' => $datesArray[$i]['period'],
                                $key1[1] => $datesArray[$i][$key1[1]],
                                $key2[1] => $datesArray[$j][$key2[1]]   
                            ));
                        }
                    }
                }

            }
        }

这产生了这个结果:

[
   {
      "period":"2014-07-16",
      "test":1
   },
   {
      "period":"2014-07-16",
      "test":1,
      "VeloxMorgana":47
   },
   {
      "period":"2014-07-15",
      "VeloxMorgana":1
   }
]

编辑:我刚刚意识到我的代码无法使用N个不同的密钥,我需要它。啊。回到绘图板!

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

$finalArray = array();
foreach ($datesArray as $date) { 
    $pushed = false;
    for ($i = 0; $i < count($finalArray); $i++) { 
        if($finalArray[$i]['period'] == $date['period']){
            $key = array_keys($date);
            $finalArray[$i][$key[1]] = $date[$key[1]];
            $pushed = true;
            break;
        }
    }
    if(!$pushed) {
        array_push($finalArray, $date);
    }
}

if(!$pushed)语句只会在第一次为真(因为$ finalArray没有元素,因此第二个for循环不会做任何事情)或者'period'值是新的。

相关问题