php - How sort json array result in codeigniter 4

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>
Answer
Solution:
You have no need to sort json array. This can be achieved simply by sorting for created_at in your model function for get result. I am assuming that created_at is column name in your table. if not then replace created_at with the column name. See code here
public function get_komen($id){
return $this->komen->where('id_user', $id)->orderBy("created_at", "desc")->get()->getResultArray();
}
check and reply
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: npm err! code 1
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.