1

Am trying to encode an array to json for use with jquery. This is the function from my model

function get_latest_pheeds() {
        $this->load->helper('date');
         $time = time();
         $q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
                        ->from('pheeds')
                        ->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
                        ->group_by('pheed_id')
                        ->order_by('datetime','desc')
                        ->limit(30);
        $rows = $q->get();
            foreach($rows->result_array() as $row) {
                $data['user_id'] = $row['user_id'];
                $data['pheed_id'] = $row['pheed_id'];
                $data['pheed'] = $row['pheed'];
                $data['comments'] = $row['comments'];
                $data['datetime'] = timespan($row['datetime'],$time);
            }
            return $data;
     }

And this is from my controller

function latest_pheeds() {
            if($this->isLogged() == true) {
            $this->load->model('pheed_model');
            $data = $this->pheed_model->get_latest_pheeds();

                echo json_encode($data);

            return false;
        }
    }

It returns only 1 row from the database when I run the code in the browser. Please help me out

2 Answers 2

2

You are overwriting data in every iteration !!

Use something like

    $data[] = array(
    'user_id' => $row['user_id'];
    'pheed_id' => $row['pheed_id']; 
    'pheed' => $row['pheed'];
    'comments' => $row['comments'];
    'datetime' => timespan($row['datetime'],$time); 
    ) ;
Sign up to request clarification or add additional context in comments.

2 Comments

foreach($rows->result_array() as $row) { $data[]['user_id'] = $row['user_id']; $data[]['pheed_id'] = $row['pheed_id']; $data[]['pheed'] = $row['pheed']; $data[]['comments'] = $row['comments']; $data[]['datetime'] = timespan($row['datetime'],$time); }
its wrong, used the one in the answer i just edited. Actually with every blank [], you increment the array index
0

This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.