【问题标题】:Merge array elements within time range - how?合并时间范围内的数组元素 - 如何?
【发布时间】:2014-03-25 06:18:50
【问题描述】:

我有一个数组,其中包含用户在网站上的活动。它包含诸如撰写 cmets、新闻和群组之类的活动。如果一个小时内写了两个(或更多)来自不同用户的 cmets,我想将这两个数组合并为一个:用户和另外 2 个对 X 发表评论。到目前为止,我的代码如下所示:

<?php

$output = array();
$output[] = array('userID' =>  12, 'txt' => sprintf('%s commented in %s', 'User1', 'Event'), 'date' => 1393080072);
$output[] = array('userID' =>  13, 'txt' => sprintf('%s commented in %s', 'User2', 'Event'), 'date' => 1393080076);
$output[] = array('userID' =>  13, 'txt' => sprintf('%s created the news %s', 'User2', 'RANDOMNEWS'), 'date' => 1393080080);
$output[] = array('userID' =>  14, 'txt' => sprintf('%s commented in %s', 'User3', 'Event'), 'date' => 1393080088);

$date = array();
foreach($output as $k => $d) {
  $date[$k] = $d['date'];
}

array_multisort($date, SORT_DESC, $output);

print_r($output);

?>

到目前为止,上面的代码按日期 (DESC) 对数组进行排序。期望的结果:一个数组:%s 和另外 2 个在...中评论,其他数组从输出中删除。因此,通过获取最新评论并检查其余 cmets 的日期,应该可以处理此问题。我只是需要一些建议。

提前致谢

【问题讨论】:

  • 有人吗?如果您需要更多信息,请随时询问。

标签: php arrays multidimensional-array merge array-merge


【解决方案1】:

根据我从您的问题中了解到的情况,我认为您想了解最近一小时内评论最新评论者的用户数量。

使用您的逻辑,array_filter 可以帮助获取最后一小时内的值。

这是你的代码的延续 -

/*
...your code...
*/

$latest_time = $output[0]['date'];
$hour_past_time = $latest_time - 3600;
$user_ids = Array();
$res=array_values(
                array_filter($output,function($arr)use($latest_time, $hour_past_time,&$user_ids){
                            if(
                                $arr["date"] <= $latest_time &&
                                $arr["date"] >= $hour_past_time &&
                                in_array($arr['userID'],$user_ids) == false
                            ){
                                $user_ids[] = $arr['userID'];
                                return true;
                            }
                        }
                )
);
echo "Users with their latest comments in the past hour- <br />";
var_dump($res);
$latest_user_id = "User".$res[0]['userID'];
$rest = count($res) - 1;
echo "<br />$latest_user_id and $rest more commented.<br />";

输出 -

Users with their latest comments in the past hour- 
array
  0 => 
    array
      'userID' => int 14
      'txt' => string 'User3 commented in Event' (length=24)
      'date' => int 1393080088
  1 => 
    array
      'userID' => int 13
      'txt' => string 'User2 created the news RANDOMNEWS' (length=33)
      'date' => int 1393080080
  2 => 
    array
      'userID' => int 12
      'txt' => string 'User1 commented in Event' (length=24)
      'date' => int 1393080072

User14 and 2 more commented.

希望这会有所帮助-

【讨论】:

  • 感谢您的精彩回答,正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 2015-04-18
相关资源
最近更新 更多