【问题标题】:Arrange an array by weeks按周排列数组
【发布时间】:2012-08-07 19:11:55
【问题描述】:

我有一个数组,其中有一个名为 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 ) ) 

【问题讨论】:

  • date('W', strtotime('07/30/12')) 可以帮助你。 php.net/date

标签: php arrays date


【解决方案1】:

这将遍历您的每个帖子,如果它们在同一周,则将它们组合在一起。

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);

【讨论】:

  • $week = date('Y W', strtotime($line['0']));如果需要按周和年排序,因为现在 2015 01 01 和 2016 01 01 在同一个数组中:)
  • 您好,是否可以为每周创建一个密钥?示例:[0] - 2019-02-26 [1] - 2019-02-27
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
相关资源
最近更新 更多