How I could change first array like final array in PHP ?
Array ( [0] => Array ( [month] => 2007-02 [clicks] => 94 )
[1] => Array ( [month] => 2007-03 [clicks] => 6930 )
开发者_如何学C[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 )
)
)
Please help ?
This type of stuff is done manually.. just break down the problem and step through it.
$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);
Set up a final array ($end
in this example), and then loop through your initial array ($start
in this example). Break down the month value to get the year and the month. Check if the year has been added to the final array, and if not create it. Then add the record as a new array built from the existing values. At the end, you've got the desired format.
$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'];
);
}
精彩评论