• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
$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).


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.