2011-08-14 92 views
1

我试图将数组编码为json以便与jQuery一起使用。 这是函数从我的模型Codeigniter结果数组只返回一行

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

这是从我的控制器

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

它从数据库中,当我运行在浏览器的代码只返回1行。 请帮我出来

回答

2

你在每次迭代覆盖数据!

使用类似

$data[] = array(
    'user_id' => $row['user_id']; 
    'pheed_id' => $row['pheed_id']; 
    'pheed' => $row['pheed']; 
    'comments' => $row['comments']; 
    'datetime' => timespan($row['datetime'],$time); 
    ) ; 
+0

它的工作阵列中的每个元素但JSON阵列现在弄乱 – MrFoh

+0

粘贴的foreach代码 – shikhar

+0

的foreach($ rows-> result_array()作为$行){ \t \t \t \t $数据[] [ 'USER_ID'] = $行['用户名']; \t \t \t \t $ data [] ['pheed_id'] = $ row ['pheed_id']; \t \t \t \t $ data [] ['pheed'] = $ row ['pheed']; \t \t \t \t $ data [] ['comments'] = $ row ['comments']; \t \t \t \t $ data [] ['datetime'] = timespan($ row ['datetime'],$ time); \t \t \t} – MrFoh

0

这是好的,但你的语法应为 'USER_ID' => $行[ 'user_ID的']