Welcome Guest, Not a member yet? Register   Sign In
$this trouble
#1

[eluser]Unknown[/eluser]
Hello,
could you tell me, what is the problem with my model?

There is a table: id, parent, messages. And I want to create an array tree. Something like this:

Code:
Array
(
    [1] => stdClass Object
        (
            [id] => 1
            [parent] => 0
            [message] => This is 1. message
            [children] => Array
                (
                    [2] => stdClass Object
                        (
                            [id] => 2
                            [parent] => 1
                            [message] => This is 2. message
                            [children] =>
                        )

                )

        )

)

so, here is my model:

Code:
class Messages_model extends CI_Model {

    private $messageArray = array();

    function get_all_messages($parent = 0)
    {
        $query = $this->db->where('parent', $id)->get('messages');

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $message)
            {
                $this->messageArray[$message->id] = $messages;
                $this->messageArray[$message->id]->children = $this->get_all_messages($message->id);
            }
        }

        if (!empty($this->$messageArray)) return $this->messageArray; else return NULL;
    }
}

Now there is *RECURSION*, and without ($this->) before all messageArray (just $messageArray) it works fine, and I dont know why. :/
Thanks for any help
#2

[eluser]WanWizard[/eluser]
Your method is returning a class property, which you then insert into that same property due to your recursive calls. If you don't use $this, it's a function local variable, so you don't have that issue.

This is not the most efficient way to build trees, Google for nested sets and adjacency lists for more efficient methods (that fetch the tree with a single query).




Theme © iAndrew 2016 - Forum software by © MyBB