我试图从php数组建立一个JSON数组这是我在控制器中的函数
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$last = end($data);
echo "[";
for($i = 0; $i < count($data); $i++) {
echo '{"user_id":"'.$data[$i][0]['user_id'].'",';
echo '"pheed_id":"'.$data[$i][0]['pheed_id'].'",';
echo '"pheed":"'.$data[$i][0]['pheed'].'",';
echo '"datetime":"'.$data[$i][0]['datetime'].'",';
if($i == count($data)) {
echo '"comments":"'.$data[$i][0]['comments'].'"}';
}else {
echo '"comments":"'.$data[$i][0]['comments'].'"},';
}
}
echo "]";
}
return false;
}
返回如下json数组
[{"user_id":"9","pheed_id":"2","pheed":"This is my first real pheed, its got potential ","datetime":"1313188898","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"10","pheed":"Thank God for stackoverflow.com ","datetime":"1313358605","comments":"0"},]
但是我不能用jquery访问它
我认为问题在于数组末尾的逗号。
与其自己编码,不如使用PHP的json_encode函数。它已经被测试和验证了很多很多次,所以你不必重新发明轮子。
已经投票了@derekerdmann,但我想我应该加上…
你的代码将工作,如果你改变:
if($i == count($data)) {
if($i == count($data) - 1) {
但是,不这样做。如果你只是把$data
数组的每个成员的所有内容放入json,那么你应该能够只json_encode($data)
。如果你只拉出某些部分,然后建立你的过滤数据和json_encode
的辅助阵列,而不是。
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$filtered_items = array();
foreach ($data as $member) {
$filtered_item = array();
$filtered_item['user_id'] = $member['user_id'];
$filtered_item['pheed_id'] = $member['pheed_id'];
...
...
$filtered_items[] = $filtered_item;
}
echo json_encode($filtered_items);
}
return false;
}