我有一个数组,其中我有一个名为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 ) )
答案 0 :(得分:4)
这将循环浏览每个帖子项目,如果它们在同一周,则将它们组合在一起。
<?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);