在时间范围内合并数组元素 - 如何?

时间:2014-02-23 19:25:36

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

我有一个数组,其中包含用户在网站上的活动。它包含诸如撰写评论,新闻和小组等活动。如果在一小时内写了两个来自不同用户的评论(或更多),我想将这两个数组合并为一个:用户和另外两个对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个注释...以及其他数组从输出中删除。因此,通过获取最新评论并检查其余评论中的日期,应该可以处理此问题。我只是需要一些建议。

提前致谢

1 个答案:

答案 0 :(得分:0)

根据我对您的问题的理解,我想您想了解最近评论员在过去一小时内评论的用户数量。

使用您的逻辑,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.

希望这有帮助 -