如果介意的话,任何人都可以告诉我如何在json数组上通过created_at进行排序。我想要最新的评论在顶部,而不是底部。这是我的代码:
模型(插入并获取评论数据(:
public function add_komen($data){
return $this->komen->insert($data);
}
public function get_komen($id){
return $this->komen->where('id_user', $id)->get()->getResultArray();
}
控制器(使用视图数组获取数据和结果(:
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'));
}
}
视图(窗体和获取结果(:
<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>
您不需要对json数组进行排序。这可以简单地通过在获取结果的模型函数中对created_at进行排序来实现。我假设created_at是表中的列名。如果不是,那么用列名替换createdAt。请参阅此处的代码
public function get_komen($id){
return $this->komen->where('id_user', $id)->orderBy("created_at", "desc")->get()->getResultArray();
}
检查并回复