Welcome Guest, Not a member yet? Register   Sign In
Appending data to a multidimensional array.
#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


Messages In This Thread
Appending data to a multidimensional array. - by El Forum - 05-03-2012, 10:28 AM
Appending data to a multidimensional array. - by El Forum - 05-03-2012, 01:11 PM



Theme © iAndrew 2016 - Forum software by © MyBB