Only last row is returned in json using codeignite

2019-08-08 08:24发布

问题:

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?

回答1:

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.



回答2:

You're assigning $arr to a new array each iteration rather than adding values to it.

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


回答3:

Your controller is not right...

//CONTROLLER
    public function v1() {

    $this->load->helper('file');

    $data = $this->load->model('model_jokes');

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($data));
}

And make sure your model created the array instead of the controller:

public function model_jokes()
{
    $jokes = $this->_load_data();
    $list = array();

        foreach ($jokes as $joke) {
            $list['joke'] = array(
                'yourdata1' => $joke->yourvariable,
                'yourdata2' => $joke->yourvariable
            );
        }
        return $list;
}

I used a private function within the model to get all data.

Hope it helps!



回答4:

I am always doing like..

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