繁体   English   中英

使用 php 回显语句构建 JSON

[英]Build JSON with php echo statements

我正在尝试从 php 阵列构建 JSON 阵列这是我的 function 在我的 Z594C18ABD5F2C6E0403C

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 function。 它已经过多次测试和验证,因此您不必重新发明轮子。

已经投票支持@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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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