Welcome Guest, Not a member yet? Register   Sign In
Appending data to a multidimensional array.
#1

[eluser]jonny68[/eluser]
Hi,

i'm struggling to build a category tree in CI and now i'm facing a new fight Smile

As you can see it loops through the result and the tree == 1 goes fine and build the array $data with the first level, the tree == 2 goes fine and build the 2 level nested under the first but i can't handle how to build the 3rd nested level, tree == 3 never work, i tried a billion things but no luck, maybe it is not possible.. Sad Let me know what you know.. Smile
Code:
foreach ($Q->result() as $row){
                          if($row->tree == 3) {
                          
                            $data[0][9]['children'][$row->parentid]['children'][$row->id]['name'] = $row->name; ///??? How can i add the last nested part of the array to the rest?
// here i put [9] manually cos that's the first key should be modified but like doesn't make sense...
                                
                          } elseif($row->tree == 2) {
                            $data[0][$row->parentid]['children'][$row->id]['name'] = $row->name;
                              
                          } elseif($row->tree == 1) {
                              $data[0][$row->id]['name'] = $row->name;
                     }
}
#2

[eluser]GrahamDj28[/eluser]
Hi,

From the sample you have provided I assume that the table has an id and parent_id column.
If this is the case you can do something like this:

Set some class variables
Code:
public $categories = array();
public $nodes = array();

Then get all of the categories and build an array like this
Code:
foreach($results as $category) {
    $this->categories[$category->id] = $category;
}

Then do something like this:
Code:
public function nodes($parent_id, $nodes=NULL) {
    foreach($this->categories as $id => $category) {
        if((int)$category->parent_id === (int)$parent_id) {
            $nodes[$id] = $category;
            $nodes[$id]['children'] = $this->nodes($id);
        }
        $this->nodes = $nodes;
    }
    
    return $nodes;
}

$this->nodes should now contain a nice nested array

You may need to tweak it to fit your own code, but should help you along. I use these methods myself for building navigation structures




Theme © iAndrew 2016 - Forum software by © MyBB