如何在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 )
)
)
请帮忙?
这类工作是手动完成的。。只需分解问题并逐步解决即可。
$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
)。细分月份值以获得年份和月份。检查年份是否已添加到最终数组中,如果没有创建,则将记录添加为根据现有值构建的新数组。最后,您得到了所需的格式。
$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'];
);
}