3
Main fields MYSQL
id, message, date
I would like it to be displayed this way in the chat
26/02/2019 - message 1 27/02/2019 - message 2 - message 3
In a way I managed to group by date, below is the form I made.
However I could not display in chat.
Until then, what I have, is this in PHP
$messages = Array ( [0] => stdClass Object ( [id] => 1 [from] => 1 [to] => 2 [message] => Mensagem 1 [is_read] => 1 [time] => 2019-02-26 10:32:55 ) [1] => stdClass Object ( [id] => 2 [from] => 2 [to] => 1 [message] => Mensagem 2 [is_read] => 1 [time] => 2019-02-27 08:33:40 ) [2] => stdClass Object ( [id] => 3 [from] => 1 [to] => 2 [message] => Mensagem 3 [is_read] => 1 [time] => 2019-02-27 08:38:20 ) ) $sorted_date = []; foreach ($messages as $message) { $chat = [ 'msg' => $message->id, 'sender' => $message->from, 'recipient' => $message->to, 'avatar' => 'no-image.jpg', 'body' => $message->message, 'time' => date("M j, Y, g:i a", strtotime($message->time)), 'type' => $message->from == $this->meu_id ? 'sender' : 'receiver', 'name' => $message->from == $this->meu_id ? 'You' : 0 ]; $timestamp = strtotime($message->time); $date = date('d-m-Y', $timestamp); if ( !isset($sorted_date[$date]) ) { //$sorted_date[$date] = [$message]; $sorted_date[$date] = [$chat]; //array_push($sorted_date, $chat); } else { //$sorted_date[$date][] = $message; $sorted_date[$date][] = $chat; } } $response = [ 'success' => true, 'thread' => $sorted_date ]; header('Content-Type: application/json'); echo json_encode($response);
print_r ($sorted_date);
Array ( [26-02-2019] => Array ( [0] => Array ( [msg] => 1 [sender] => 1 [recipient] => 2 [avatar] => no-image.jpg [body] => Mensagem 1 [time] => Feb 26, 2019, 10:32 am [type] => sender [name] => You ) ) [27-02-2019] => Array ( [0] => Array ( [msg] => 2 [sender] => 2 [recipient] => 1 [avatar] => no-image.jpg [body] => Mensagem 2 [time] => Feb 27, 2019, 8:33 am [type] => receiver [name] => 0 ) [1] => Array ( [msg] => 3 [sender] => 1 [recipient] => 2 [avatar] => no-image.jpg [body] => Mensagem 3 [time] => Feb 27, 2019, 8:38 am [type] => sender [name] => You ) ) )
This is what I have on the return of AJAX
success: (function (response) {
thread = response.thread;
$('.message-box').html('');
$.each(thread, function () {
/* esta parte do código funciona, quando as mensagens não estão agrupadas */
html = '<div class="message ' + this.type + '">' +
' <span>' + this.body + '</span>' +
' <span class="metadata">' +
' <span class="time">' + this.time + '</span>' +
' </span>' +
'</div>';
$('.message-box').append(html);
});
}),
Do the main values return? Type, dates return?
– adventistaam
Yes, see the print_r
– Wagner Fillio
I meant in ajax. I’m sorry
– adventistaam
See https://i.imgur.com/P1u7mzt.png console
– Wagner Fillio
Try as follows: `$. each(thread, Function(i, j){ console.log( j }) see what returns
– adventistaam
Here it returns me this: https://i.imgur.com/L7B33K8.png
– Wagner Fillio
Let’s go continue this discussion in chat.
– adventistaam