开发者

Multi-dimension array format change In PHP

开发者 https://www.devze.com 2023-03-10 20:16 出处:网络
How I could change first array like final array in PHP ? Array ( [0] => Array ( [month] => 2007-02 [clicks] => 94 )

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'];
    );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消