Welcome Guest, Not a member yet? Register   Sign In
Some help with foreach and result_arry()
#1

[eluser]mikeymayhem[/eluser]
Hi Im fairly new to php and CI in general and have been having some trouble with some code i have been writing on wondered if anybody could help me out a little.
I ventured into php and CI after an idea for a website came to me a few months ago. I have managed to achieve all the features i want on a basic level and have now began trying to improve the functionality of the website a little.

part of the website runs a news section which allows registered users to post comments. Bascially im trying to pull 2 comments from the database to be displayed with its relative news post within a foreach loop. heres how i went about it

Controller
Code:
function index() {
        
        $get_posts = $this->site_model->get_posts();

        //fetch new comments an assign to comments key in the posts array
        foreach($get_posts->result_array() as $key => $post){
            $posts['key'] = $post;
            $posts['key']['comments'] = $this->site_model->get_comments($post['id']);
        }
        
        $data['get_posts'] = $posts;
        
        //load the view
        $data['main_content'] = 'site/site_view';
        $this->load->view('includes/template',$data);
    }

}
Code:
The Model:
    function get_posts() {
        $this->db->where('active', '1');
        $this->db->order_by('post_date','desc');
        return $this->db->get('news');    
    }

    function get_comments($id) {

        $this->db->where('news_id', $id);
        $this->db->where('active', '1');
        $this->db->order_by('post_date','desc');
        $this->db->limit('2');
        return $this->db->get('news_comments');
        
    }
Code:
The View:
<?php foreach($get_posts as $post):?>
   <p>&lt;?php echo $post['id']; ?&gt;</p>
    <p> &lt;?php echo $post['title']; ?&gt;</p>
    &lt;?php foreach($post['comments']->result_array() as $comment): ?&gt;
        <p>&lt;?php echo $comment['id'];?&gt;</p>
        <p>&lt;?php echo $comment['user_id'] ?&gt;</p>
    &lt;?php endforeach; ?&gt;
&lt;?php endforeach; ?&gt;
This only seems to pull one result from the news table when there are several in there. Any help or suggestions would be greatly apprciated

Thanks in advance
#2

[eluser]danmontgomery[/eluser]
Do you mean to do:

Code:
$posts[$key] = $post;
$posts[$key]['comments'] = $this->site_model->get_comments($post['id']);

?
#3

[eluser]mikeymayhem[/eluser]
ah yeah my bad Big Grin hopefully that is my problem will post reply if so thanks for the quick rsponse
#4

[eluser]mikeymayhem[/eluser]
thats solved the problem, how silly sorry for the time waster!!! is this the best way to achive the results im after out of interest??




Theme © iAndrew 2016 - Forum software by © MyBB