Am trying to build a JSON array from a php array This is my function in my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('p开发者_运维百科heed_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;
}
It returns a json array like this
[{"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"},]
But i cant seem to access it with jquery
I believe the problem rests with the trailing comma at the end of your array.
Rather than try to encode it yourself, use PHP's json_encode function. It's been tested and verified many, many times, so you don't have to reinvent the wheel.
Already voted up @derekerdmann, but thought I would add...
Your code will work, if you change:
if($i == count($data)) {
to
if($i == count($data) - 1) {
But, don't do that. If you are just putting everything from each member of the $data
array into the json, then you should be able to just json_encode($data)
. If you are only pulling out certain parts, then build up a secondary array of your filtered data and json_encode
that instead.
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;
}
精彩评论