只有最后一行在json中使用codeigniter返回 [英] Only last row is returned in json using codeigniter

查看:112
本文介绍了只有最后一行在json中使用codeigniter返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用codeigniter返回json数据,我将在javascript中使用该json。现在的问题是,它只返回数据库表中的最后一行,并从该行创建一个json格式。这是我的代码在控制器

  public function v1(){
$ this-> load-> model ('model_jokes');

$ jokes = $ this-> model_jokes-> readJokes();
foreach($ jokes as $ joke){
$ arr = array(
array(
'title'=> $ joke-> title,
' description'=> $ joke-> joke

);
}
echo json_encode($ arr);
}

如何使我从数据库检索的所有数据

$ p

 <$> 

c $ c> $ arr = array();
foreach($ jokes as $ joke){
$ arr [] = array(
'title'=> $ joke-> title,
'description'=> ; $ joke-> joke
);
}

在您的代码段中,您将覆盖 $ arr



这篇文章中的上述代码段会将所有条目附加到数组 $ arr ,你可以稍后编码为json。


I am trying to return json data using codeigniter which I will later use that json in javascript. Now the problem is that it only returns the last row from database table and make a json format from that one row. Here is my code in controller

public function v1 () {
    $this->load->model('model_jokes');

    $jokes = $this->model_jokes->readJokes();
    foreach ($jokes as $joke) {
        $arr = array(
                array(
                    'title' => $joke->title,
                    'description' => $joke->joke
                )
            );
    }
    echo json_encode($arr);
}

how can I make it so that all data that I am retrieving from database is returned in json?

解决方案

Try

$arr = array();
foreach ($jokes as $joke) {
  $arr[] = array (
    'title' => $joke->title,
    'description' => $joke->joke
  );
}

In your snippet you are overwriting $arr with each iteration in your loop.

The above snippet in this post will append all entries to the array $arr which you can later encode to json.

这篇关于只有最后一行在json中使用codeigniter返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆