结合多个阵列 - 基于数量?

时间:2013-02-13 14:22:12

标签: php arrays merge

这似乎很容易,但无法弄清楚如何做到这一点。当前数组数据按日期和按日期列出,因此我需要合并所有日期:日,月,6个月,1年。我需要将数组数据排列成下面的第二个数组。


    array
      0 => enter code here
        array
          '1_day' => int 37
      1 => 
        array
          '30_day' => int 3275
      2 => 
        array
          '180_day' => int 3908
      3 => 
        array
          '1_year' => int 6933
      4 => 
        array
          'date' => string '2013-02-13' (length=10)
      5 => 
        array
          '1_day' => int 46
      6 => 
        array
          '30_day' => int 3134
      7 => 
        array
          '180_day' => int 3764
      8 => 
        array
          '1_year' => int 6820
      9 => 
        array
          'date' => string '2013-02-12' (length=10)
      10 => 
        array
          '1_day' => int 61
      11 => 
        array
          '30_day' => int 3127
      12 => 
        array
          '180_day' => int 3750
      13 => 
        array
          '1_year' => int 6807
      14 => 
        array
          'date' => string '2013-02-11' (length=10)

enter code here

3 个答案:

答案 0 :(得分:0)

Try this one....

$result = array();     
 $i = 0;
foreach($data as $key => $d) 
{
    $result[$i]['1_day'] = $data[$key]['1_day'];
    $result[$i]['30_day'] = $data[$key+1]['30_day'];
    $result[$i]['180_day'] = $data[$key+2]['180_day'];
    $result[$i]['1_year'] = $data[$key+3]['1_year'];
    $result[$i]['date'] = $data[$key+4]['date'];
    $key = $key+5;
    $i++;
  }

答案 1 :(得分:0)

未经测试,但这应该让你接近:

<?php

$result = array();

for ($i = 0; $i <= count($array); $i++)
{
    if ($array[$i] == 'date')
    {
        $result[] = array(
            '1_day'    => $array[$i-4],
            '30_day'   => $array[$i-3],
            '180_day'  => $array[$i-2],
            '1_year'   => $array[$i-1],
            'date'     => $array[$i],
        );
    }
}

答案 2 :(得分:0)

另一种方法:

<?php

$count = count($inArray);

//In place subarray merger, by this you don't have to modify keys every time they change.
//Constraint: A sub-array at every index.

for ($idx =0, $jdx =0; $idx < $count; $idx +=5, $jdx++) {
    $inArray[$jdx] = array_merge($inArray[$idx],
                                $inArray[$idx +1],
                                $inArray[$idx +2],
                                $inArray[$idx +3],
                                $inArray[$idx +4]);
}

array_splice ($inArray, $count/5);

/* OR into another array */

for ($idx =0, $jdx =0; $idx < $count; $idx +=5, $jdx++) {
    $newArray[$jdx] = array_merge($inArray[$idx],
                                $inArray[$idx +1],
                                $inArray[$idx +2],
                                $inArray[$idx +3],
                                $inArray[$idx +4]);
}

?>