2012-08-07 61 views
2

我有一个数组,其中有一个叫date的字段,我需要的是将所有这些数组分成几个星期。这样做有可能吗?这里是我的代码:按星期排列数组

function getWeeks($query){ 
    $postdate = $query['response']['posts']['date']; 


    return $posts; 
} 

这里是我的阵列的一部分:

Array ([date] => 07/30/12 [message] => test [post_id] => 1 [impressions] => Array ([0] => 9638) [consumptions] => Array ([0] => 38) [storytellers] => Array ([0] => 6) [engaged_users] => Array ([0] => 31) [story_adds] => Array ([0] => 6) [impressions_unique] => Array ([0] => 4700) [comment] => Array ([0] => 1) [like] => Array ([0] => 5) [share] => Array ([0] => 0) [virality] => Array ([0] => 0) [lifetime] => Array ([0] => 0) [affinity] => Array ([0] => 0)) 

Array ([date] => 07/30/12 [message] => test2 [post_id] => 2 [impressions] => Array ([0] => 10552) [consumptions] => Array ([0] => 47) [storytellers] => Array ([0] => 5) [engaged_users] => Array ([0] => 44) [story_adds] => Array ([0] => 5) [impressions_unique] => Array ([0] => 4982) [comment] => Array ([0] => 0) [like] => Array ([0] => 4) [share] => Array ([0] => 1) [virality] => Array ([0] => 0) [lifetime] => Array ([0] => 0) [affinity] => Array ([0] => 0)) 
+2

'日期( 'W',的strtotime('07/30/12' ))'可以帮助你。 http://php.net/date – 2012-08-07 19:15:39

回答

4

通过每个岗位的项目,并将它们组合的这种将循环起来,如果他们是在同一个星期。

View an Example

<?php 

$posts = array(
    array('date' => '7/30/10', 'title' => 'july post'), 
    array('date' => '7/19/10', 'title' => 'another post in july'), 
    array('date' => '7/22/10', 'title' => 'sup, this will be with another post') 
); 

$grouped_posts = array(); 

foreach($posts as $post) { 
    // @see http://us2.php.net/manual/en/function.date.php 
    $week = date('W', strtotime($post['date'])); 

    // create new empty array if it hasn't been created yet 
    if(!isset($grouped_posts[$week])) { 
    $grouped_posts[$week] = array(); 
    } 

    // append the post to the array 
    $grouped_posts[$week][] = $post; 
} 

print_r($grouped_posts); 
+1

$ week = date('Y W',strtotime($ line ['0']));如果需要按星期和年份分类,现在2015 01 01和2016 01 01在同一阵列中:) – Arnoldas 2017-08-23 09:05:58