简体   繁体   中英

I am getting json data in a different format in codeigniter. Why?

I am trying to make and return json data using codeigniter. I want to receive that data in this format

[
  {
     'title': 'this is title',
     'desc':  'THis is desc'
  },
   {
     'title': 'this is title',
     'desc':  'THis is desc'
  }
]

But I am receiving it this way

[[{"title":"this is title","desc":"this is desc"}],[{"title":"this is title","description":"this is desc"}]]

how can I change this format to above one?

here is my code

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

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

Make the assignment inside foreach as

$arr[] = array(
  'title' => $joke->title,
  'description' => $joke->joke
);

Otherwise you will get a multi-dimensional array for each $joke .

You are adding array of array element each time in a loop. Instead just add single array.

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

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

尝试:

echo '<pre>'.json_encode($arr).'</pre>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM