-1

我想按日期汇总数据组

示例数据

{"reqtime":"Monday, July 30, 2012 08:55:45","user_id":"9704"},
{"reqtime":"Tuesday, September 4, 2012 11:07:11","user_id":"9717"},
{"reqtime":"Thursday, September 13, 2012 07:41:41","user_id":"9720"},
{"reqtime":"Friday, October 12, 2012 10:20:19","user_id":"9731"},
{"reqtime":"Friday, October 19, 2012 10:20:14","user_id":"9726"},
{"reqtime":"Monday, November 26, 2012 18:42:00","user_id":"9701"}
{"reqtime":"Thursday, December 6, 2012 11:33:52","user_id":"9728"},
{"reqtime":"Monday, December 10, 2012 02:55:53","user_id":"10282"},
{"reqtime":"Monday, December 10, 2012 03:02:24","user_id":"10284"},
{"reqtime":"Monday, December 10, 2012 04:02:57","user_id":"10286"},
{"reqtime":"Monday, December 10, 2012 04:18:29","user_id":"9944"},
{"reqtime":"Monday, December 10, 2012 05:22:38","user_id":"10292"},
{"reqtime":"Monday, December 10, 2012 05:23:05","user_id":"10291"},

变成这样

例子 :

dec 10 : 6 user_id /*( **sum user_id but sorting by date** )*/

这是我的代码/脚本尚未求和,n 尚未编码为 json :

$query = "SELECT * FROM  `users_demoid` order by reqtime LIMIT 0 , 100";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());

// get data and store in a json array
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $date=date("l, F j, Y H:i:s",$row['reqtime']);
    $orders[] = array(
        'reqtime' => $date,
        'user_id' => $row['user_id']
      );
}

提前致谢

4

2 回答 2

0
$arr = json_decode($json_arr) ;
$arr_res=array();
$i=0;
 foreach($arr as $stdobj)
   {
      $search = $stdobj->reqtime;
      $arr_res[$i]['user_id']=$stdobj->user_id;
      foreach($arr as $stdobj2 )
      {
            if($search == $stdobj2->reqtime)
            {
              $arr_res[$i]['sum'] +=1;
             } 
      }
   $i++
  }
于 2013-01-15T05:07:45.517 回答
0

我假设您的示例数据实际上是一个 JSON 数组。我们将其称为$json_data示例。我相信您已经知道可以使用json_decode. 我们将 JSON 转换为关联数组,因为我碰巧喜欢它们而不是StdObjects:

$array_data = json_decode($json_data, TRUE);

这将为您提供数据的多维数组 - 包含每个记录的数组作为关联记录的数组,其中键为reqtimeand user_id,例如:

Array
(
    [0] => Array
        (
            [reqtime] => Monday, December 10, 2012 02:55:53
            [user_id] => 10282
        )

    [1] => Array
        (
            [reqtime] => Monday, December 10, 2012 02:55:53
            [user_id] => 10282
        )

)

现在我们有了可以迭代的格式的数据,所以我们会这样做。在每次迭代中,我们将转换reqtime为方便的格式进行比较——基本上只是去掉时间分量。然后,如果该日期在该数组中不存在,我们将把它作为键添加到结果数组中,如果存在,则增加它的值:

$result = array();
foreach($array_data as $data_record) {
  $date = date('M d', strtotime($data_record['reqtime']));
  if (isset($result[$date])) {
    $result[$date]++;
  } else {
    $result[$date] = 1;
  }
}

请注意,日期格式M d将仅包含月份和日期(例如“Dec 10”),但不包含年份,因此如果您的数据可能有重叠的日期(例如“Dec 10 2011”和“Dec 10” 2012”),那么您需要考虑到这一点。

此外,这将计算每个日期有多少条记录,而不是有多少唯一用户。如果同一用户有可能在同一日期出现在多条记录中,但您只想计算一次用户,那么您还需要额外的逻辑。

我将把这两个作为练习留给你,因为它们不是原始问题的一部分。

于 2013-01-15T05:16:38.017 回答