Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build JSON with php echo statements

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('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;
    }

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

like image 792
MrFoh Avatar asked Jan 16 '26 22:01

MrFoh


1 Answers

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.

like image 192
derekerdmann Avatar answered Jan 19 '26 14:01

derekerdmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!