2014-01-23 16 views
0

由於從MySQL的輸出我有一個這樣的數組:如何找到在一年最後一天的日期數組(PHP)

Array 
(
    [0] => Array 
     (
      [name] => Date 
      [data] => Array 
       (
        [0] => 2009-07-01 
        [1] => 2009-08-01 
        [2] => 2009-09-01 
        [3] => 2010-10-01 
        [4] => 2010-11-01 
        [5] => 2010-12-01 
        [6] => 2011-01-01 
        [7] => 2011-02-01 
        [8] => 2012-03-01 
        [9] => 2012-04-01 
        [10] => 2012-05-01 
       ) 
     ) 

    [1] => Array 
     (
      [name] => Counts 
      [data] => Array 
       (
        [0] => 13 
        [1] => 13 
        [2] => 15 
        [3] => 16 
        [4] => 17 
        [5] => 18 
        [6] => 19 
        [7] => 11 
        [8] => 14 
        [9] => 14 
        [10] => 15 
       ) 
     ) 
) 

爲了進一步發展我需要找到每個最高的日期年。如何查找每年的最後日期,並從'counts'數組中獲取它的值。對於上面的代碼,我想實現這樣的事情:

Array 
(
    [0] => Array 
     (
      [name] => Date 
      [data] => Array 
       (
        [1] => 2009-09-01 
        [2] => 2010-12-01 
        [3] => 2011-02-01 
        [4] => 2012-05-01 
       ) 
     ) 

    [1] => Array 
     (
      [name] => Counts 
      [data] => Array 
       (
        [1] => 15 
        [2] => 18 
        [3] => 11 
        [4] => 15 
       ) 
      ) 
+5

向我們展示您試過的東西。這並不難,所以你肯定嘗試過一些東西。 –

+0

是的,一個簡單的谷歌搜索不會傷害,我認爲這可能會幫助你http://stackoverflow.com/questions/11012891/how-to-get-most-recent-date-from-an-array-of-日期 –

回答

0

php有最大的功能。閱讀關於它here它是非常容易使用您的需求;

0
$arr = array('... your array ...'); 
$date = array(); 
$count = array(); 
foreach ($arr[0]['data'] as $key => $value) { 
    $year = substr($value, 0, 4); 
    if (!$date[$year] || $date[$year] < $value) { 
     $date[$year] = $value; 
     $count[$year] = $arr[1]['data'][$key]; 
    } 
} 
$date = array_values($date); //reset the keys 
$count = array_values($count); //reset the keys 
$res = array(
    array(
     'name'=>'Date', 
     'data'=>$date, 
    ), 
    array(
     'name'=>'Count', 
     'data'=>$count, 
    ) 
); 
print_r($res); 
相關問題