0

I am working with Php and json,Right now i am getting data from database.Here is my code.

$CommentTime= $this->M_main->GetFeedsCommentTime($FeedId);
echo json_encode($CommentTime); 

So i am getting following result

[{"id":"475","CreatedAt":"1636953999"},
{"id":"474","CreatedAt":"1636953988"},
{"id":"473","CreatedAt":"1636953977"}]

And i want to get "time ago" concept(want to check comment time) So i am using foreach loop and pass "CreatedAt" for get "time"(how minutes/hour/weeks ago)

foreach($CommentTime as $k => $cmt)
        {
    $CreatedAt=$cmt['CreatedAt'];
    $PostedAts=$CreatedAt;
                                            
    $time_ago = $PostedAts;
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $seconds    = $time_elapsed ;
    $minutes    = round($time_elapsed / 60 );
    $hours      = round($time_elapsed / 3600);
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );
    // Seconds
    if($seconds <= 60){
            $PostedTime= "just now";
    }
    //Minutes
    else if($minutes <=60){
        if($minutes==1){
                $PostedTime= "one minute ago";
        }
        else{
                $PostedTime= "$minutes minutes ago";
        }
    }
    //Hours
    else if($hours <=24){
            if($hours==1){
                $PostedTime= "an hour ago";
                }else{
                    $PostedTime= "$hours hrs ago";
                    }
    }

I am getting Postedtime correctly but how can i merge this(posted time) with above result,I want following output as result

[{"id":"475","CreatedAt":"1636953999","Time:"5 minutes ago"},
{"id":"474","CreatedAt":"1636953988","Time:"10 minutes ago"},
{"id":"473","CreatedAt":"1636953977","Time:"15 minutes ago"}]

How can i do this ? Thank you in advance

2 Answers2

0

Replace this foreach($CommentTime as $k => $cmt) to foreach ($CommentTime as $k => &$cmt) and place in the end of foreach this line: $cmt['Time'] = $PostedTime;

silentwasd
  • 339
  • 1
  • 6
0

You can do something like this.

foreach($CommentTime as &$cmt) {

   // Your Code Comes Here

   $cmt['Time'] = $PostedTime;

}
Dula
  • 1,276
  • 5
  • 14
  • 23