我在codeigniter中以不同的格式获取json数据。为什么?

时间:2012-10-31 06:39:07

标签: php json codeigniter

我正在尝试使用codeigniter制作并返回json数据。我想以这种格式接收数据

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

但我这样收到它

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

如何将此格式更改为以上格式?

这是我的代码

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);
}

3 个答案:

答案 0 :(得分:1)

foreach内的作业设为

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

否则,您将获得每个$joke的多维数组。

答案 1 :(得分:1)

每次在循环中添加数组元素数组。而只是添加单个数组。

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);
}

答案 2 :(得分:0)

尝试:

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