Codeigniter:在循环

时间:2016-08-23 21:56:52

标签: php arrays codeigniter

我从foreach循环中的posts表中获取新闻项,并且从附件表中获取与任何此项相关的附件。

我想像这样构建数组

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
        )

)

现在我如何修改我的代码,使得与该新闻相关的每个新闻项目和附件的格式正确如上所述

1 个答案:

答案 0 :(得分:2)

使用$data = array();在处理后存储您的数据

只需修改行

即可

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

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

并使用Array push $ res to $ total;

因为在每次循环之后你的$ res已被覆盖但你没有存储它

完整代码

$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>";