if mind, anyone can tell me how to sort by created_at on json array.
I want the newest comment on top, not on the bottom.
Here is my code :
Model (to insert and get comment data):
public function add_komen($data){
return $this->komen->insert($data);
}
public function get_komen($id){
return $this->komen->where('id_user', $id)->get()->getResultArray();
}
Controller (get data & get result using array for views):
public function do_add_komentar(){
$data['nama_komentar'] = $this->request->getPost('nama');
$data['isi_komentar'] = $this->request->getPost('komentar');
$data['id_user'] = $_SESSION['id_user'];
$update = $this->UndanganModel->add_komen($data);
if($update){
echo json_encode(array('status' => 'sukses','nama' => \esc($data['nama_komentar']),'komentar' => \esc($data['isi_komentar']) ));
}else{
echo json_encode(array('status' => 'gagal'));
}
}
Views (Form & Get Result):
<input id="nama" type="text" class="form-control mt-2" placeholder="Nama Anda" required>
<textarea id="komentar" class="form-control" id="exampleFormControlTextarea1" placeholder="Pesan anda.." rows="3" required></textarea>
<button id="submitKomen" class="btn btn-primary btn-block" >Kirim</button>
<div class="layout-komen">
<?php foreach($komen as $key => $data) { ?>
<div class="komen" >
<div class="col-12 komen-nama">
<?= \esc($data['nama_komentar']); ?>
</div>
<div class="col-12 komen-isi">
<?= \esc($data['isi_komentar']); ?>
</div>
</div>
<?php } ?>
</div>
My Answer:
To sort the JSON array by the `created_at` field in descending order (newest comment on top), you can modify your `get_komen` method in the Model as follows:
php
public function get_komen($id){
return $ $this->komen->where('id_user', $id)->orderBy('created_at', 'DESC')->get()->getResultArray();
}
By adding `orderBy('created_at', 'DESC')`, you are sorting the results by the `created_at` field in descending order.
This will ensure that the newest comments are displayed at the top when you loop through the `$komen` array in your View.
Rate this post
4 of 5 based on 8966 votesComments