Welcome Guest, Not a member yet? Register   Sign In
multi-dimensional arrays/objects
#1

[eluser]Unknown[/eluser]
Hi all,

I'm a total newb to codeigniter and php but loving it so far. Totally stuck at the moment though!

Lets say I have a posts table, and a comments table and on my view I want to show the last 10 posts along with the appropriate comments under each of those posts. I have gotten totally confused, hence the code might also be confusing esp with variable names, but this is the way the two functions site in my model at the moment:-

Code:
function get_posts($offset=0)
    {
        /* get all posts and do a join to get the first name and lastname of author */
        $this->db->select('*');
        $this->db->join('users', 'users.id = newsfeed.news_author_id');
        $this->db->order_by('news_id', 'desc');
        $query = $this->db->get('newsfeed', 10, $offset);
        $query = $query->result();

        /* pass the results object to get_comment */
        $result = $this->get_comment($query);
        return $result;
            
    }

    function get_comment($data)
    {
        foreach($data as $post)
        {
            $this->db->select('*');
            /*get all comments for the specified post */
            $this->db->where('comments.comments_parent_id =', $post->news_id);
            $this->db->join('users', 'users.id = comments.comments_author_id');
            $this->db->order_by('comments_datetime', 'desc');
            $q = $this->db->get('comments');
                if($q->num_rows() > 0)
                {
                $post['comments']=$q->result();
                }
    }
    return $data;
    }

is it actually possible to add another set of results inside existing an existing results object like this? just how wrong am i?

many thanks

steve
#2

[eluser]Georgi Budinov[/eluser]
Firstly use:

Code:
$query->result_array(); and $q->result_array();

instead of

Code:
$query->result(); and $q->result();

Secondly modifying $post in the foreach loop doesn't modify $data! Do it like this:

Code:
foreach($data as $ind=>$post)
{
    $data[$ind]['comments'] = ...
}

And last but not least you are making bunch of queries to the db. It is better to make just one, left joining the two tables and iterating through the result.
#3

[eluser]Unknown[/eluser]
Thank you very much for the reply georgi, all working now!

I'm going to learn how to deal with joins and iteration now.




Theme © iAndrew 2016 - Forum software by © MyBB