多维数组格式更改在PHP中

时间:2011-06-07 15:12:21

标签: php arrays multidimensional-array key-value

如何在PHP中更改第一个数组,如最终数组?

Array ( [0] => Array ( [month] => 2007-02 [clicks] => 94 ) 
        [1] => Array ( [month] => 2007-03 [clicks] => 6930 )
        [2] => Array ( [month] => 2007-04 [clicks] => 4 ) 
        ....
        [11] => Array ( [month] => 2008-01 [clicks] => 1008)
        [12] => Array ( [month] => 2008-02 [clicks] => 7 ) 
      )

Array ( [2007] => Array(
                        [0] => Array ( [month] => 1 [clicks] => 94 ) 
                        [1] => Array ( [month] => 2 [clicks] => 6930 )
                        [2] => Array ( [month] => 3 [clicks] => 4 )
                        ...
                       ),
        [2008] => Array(
                        [0] => Array ( [month] => 1 [clicks] => 1008) 
                        [1] => Array ( [month] => 2 [clicks] => 7 )
                       )
      )

请帮帮忙?

2 个答案:

答案 0 :(得分:2)

这种类型的东西是手动完成的。只需解决问题并逐步完成。

$start = array();
$start[] = array("month"=>"2007-02","clicks"=>94);
$start[] = array("month"=>"2007-03","clicks"=>6930);
$start[] = array("month"=>"2007-04","clicks"=>4);
.....this is just for setup of testing.... 

$end = array();

foreach ($start as $record) {
    $keys = explode("-",$record['month']);
    $year = $keys[0];
    $month = $keys[1];
    if (!isset($end[$year])) $end[$year] = array();
    $end[$year][] = array("month"=>$month, "clicks"=>$record['clicks']);
}

var_dump($end);

设置最终数组(在此示例中为$end),然后遍历初始数组(在此示例中为$start)。分解月份值以获得年份和月份。检查年份是否已添加到最终数组,如果没有创建它。然后将记录添加为根据现有值构建的新数组。最后,你得到了所需的格式。

答案 1 :(得分:0)

$newArray = array();
foreach($oldArray as $row) {
    list($year, $month) = explode($row['month']);
    $newArray[$year][(int)$month] = array( 
        'month' => (int)$month,  // this is in fact redundant - you have it in the index aleready
        'clicks' => $row['clicks'];
    );
}