1

I am fetching news items from posts table in foreach loop and attachments related to any this item are being fetched from attachments table .

i want to structure array like this

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
           )

        )

this is how i am doing my loop

$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();

            }

        }

this is what i get

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
        )

)

Now how do i modify my code in a way that each news item and attachment related to that news are formatted properly as i mentioned above

1
  • This looks like you can just optimize your query by using a left join Commented Aug 23, 2016 at 22:00

1 Answer 1

2

Use $data = array(); to store your data after process

Just modify the line

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

to

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

And use Array push $res to $total;

Because after each loop your $res has been overided but you don't store it

Full of code

$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>";
Sign up to request clarification or add additional context in comments.

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.