2016-08-23 59 views
1

我正在從foreach循環中的帖子表中獲取新聞項目,並且從附件表中獲取與任何此項目相關的附件。Codeigniter:在循環中添加數組索引

我想結構數組這樣

Array 
(
    [news] => stdClass Object 
     (
      [id] => 95 
      [date] => 2016-07-29 
      [title] => This is first news 
      [content] => This is first news details 
      [type] => news 
      ['attachment'] => stdClass Object 
      (
       [id] => 25 
       [attachment_id] => 95 
       [type] => news 
       [path] => Jellyfish23.jpg 
      ) 

     ) 

我這是怎麼做的我的循環

$posts=$this->db->get_where('posts',array('type'=>$type)); 
     if($posts->num_rows()>0){ 
      foreach ($posts->result() as $key=> $value) { 
       echo $value->id; 
       $res['news']=$posts->row(); 
       $result = $this->db->get_where('attachments', array('attachment_id'=>$value->id)); 
       $res['attachment']= $result->row(); 

      } 

     } 

這是我得到

Array 
(
    [news] => stdClass Object 
     (
      [id] => 95 
      [date] => 2016-07-29 
      [title] => This is first news 
      [content] => This is first news details 
      [type] => news 
     ) 

    [attachment] => stdClass Object 
     (
      [id] => 25 
      [attachment_id] => 97 
      [type] => news 
      [path] => Jellyfish23.jpg 
     ) 

) 

現在我該怎樣修改我的代碼的方式,每個新聞項目和附件相關的新聞格式正確,因爲我上面提到

+0

這就像你可以通過使用左優化您的查詢加盟 – killstreet

回答

2

使用$data = array();您的數據存儲處理後

就修改該行

$res['attachment']= $result->row();

$res['news']['attachment']= $result->row();

並使用陣推$水庫至$總量;

因爲每個循環之後你$資源已經overided但你沒有保存它

完整的代碼

$posts=$this->db->get_where('posts',array('type'=>$type)); 
$data = array(); 

if($posts->num_rows()>0){ 
    foreach ($posts->result() as $key=> $value) { 
     echo $value->id; 
     $res['news']=$posts->row(); 
     $result = $this->db->get_where('attachments', array('attachment_id'=>$value->id)); 
     $res['news']['attachment']= $result->row(); 
     array_push($data, $res); 
    } 
} 

echo "<pre>"; 
var_dump($data); 
echo "</pre>";