【问题标题】:php array sorting by date stdClass Objectphp数组按日期stdClass对象排序
【发布时间】:2012-08-27 17:47:33
【问题描述】:

我有一个这样的数组:

Array ( [0] => stdClass Object ( [id] => 41 [title] => test2 [alias] => test2 [catid] => 8 [published] => 1 [introtext] =>
test2

[fulltext] => [video] => [gallery] => [extra_fields] => [] [extra_fields_search] => [created] => 2012-08-27 16:37:51 [created_by] => 62 [created_by_alias] => [checked_out] => 0 [checked_out_time] => 0000-00-00 00:00:00 [modified] => 0000-00-00 00:00:00 [modified_by] => 0 [publish_up] => 2012-08-27 16:37:51 [publish_down] => 0000-00-00 00:00:00 [trash] => 0 [access] => 1 [ordering] => 15 [featured] => 0 [featured_ordering] => 0 [image_caption] => [image_credits] => [video_caption] => [video_credits] => [hits] => 0 [params] => JParameter Object ( [_raw:protected] =>  

该数组中的等(其中有很多东西)。

现在显示是这样的

项目 |日期
项目 |日期
项目 |日期

我想要做的是获取该数组并按聚合日期对其进行排序

这样想

聚合日期
项目 |日期
项目 |日期
聚合日期
项目 |日期
项目 |日期

如果有这个数组,这甚至可能吗?

【问题讨论】:

  • 您只想对创建日期进行“分组”吗?我没有看到对象中的任何测量值表明它们在 sum() 或 avg() 等聚合函数中很有用。项目是否重复?猜猜我不知道“聚合日期”与您的示例所需输出中的“日期”相比。

标签: php arrays joomla stdclass


【解决方案1】:

这是你要找的吗?

$newArray = array();
foreach ($myArrayOfStdClasses as $key => $obj) {
    $newArray[date('Y-m-d', strtotime($obj->created]))[] = array('title' => $obj->tile, 'date' => $obj->created);
}

【讨论】:

    【解决方案2】:

    你可以使用 usort 来定义你的排序函数:

    usort($items, function($item1, $item2){
       if($item1->created == $item2->created)
          return 0;
    
       return $item1->created < $item2->created ? -1 : 1;
    });
    

    这只会对它们进行排序。然后在循环输出时,您可以根据天、小时、月进行聚合...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多