How to sort a flat array in a multi-dimensional tree

I have a table like

id catagory suboff 1 software 0 2 programming 1 3 Testing 1 4 Designing 1 5 Hospital 0 6 Doctor 5 7 Nurses 5 9 Teaching 0 10 php programming 2 11 .net programming 2 

How to write code to get all this information in a multidimensional array based on suboff as follows:

 -software --programming ---php programming --- .net programming --testing --designing -hospital --doctor --nurses -teaching 
+4
source share
10 answers

Assuming MySQL is your DB engine:

 // We'll need two arrays for this $temp = $result = array(); // Get the data from the DB $table = mysql_query("SELECT * FROM table"); // Put it into one dimensional array with the row id as the index while ($row = mysql_fetch_assoc($table)) { $temp[$row['id']] = $row; } // Loop the 1D array and create the multi-dimensional array for ($i = 1; isset($temp[$i]); $i++) { if ($temp[$i]['suboff'] > 0) { // This row has a parent if (isset($temp[$temp[$i]['suboff']])) { // The parent row exists, add this row to the 'children' key of the parent $temp[$temp[$i]['suboff']]['children'][] =& $temp[$i]; } else { // The parent row doesn't exist - handle that case here // For the purposes of this example, we'll treat it as a root node $result[] =& $temp[$i]; } } else { // This row is a root node $result[] =& $temp[$i]; } } // unset the 1D array unset($temp); // Here is the result print_r($result); 

Use references for such a task.

+3
source

Demo: http://ideone.com/vk4po

 $array = array( array('1','software','0'), array('2','programming','1'), array('3','Testing','1'), array('4','Designing','1'), array('5','Hospital','0'), array('6','Doctor','5'), array('7','Nurses','5'), array('9','Teaching','0'), array('10','php programming','2'), array('11','.net programming','2') ); function menu_sort($results, $master = 0) { $open = array(); $return = NULL; foreach($results as $result) { if($result[2] == $master){ if(!$open){ $return .= '<ul>'; $open = true; } $return .= '<li>'.$result[1]; $return .= menu_sort($results, $result[0]); $return .= '</li>'; } } if($open) $return .= '</ul>'; return $return; } echo menu_sort($array); 

Result...

 software programming php programming .net programming Testing Designing Hospital Doctor Nurses Teaching 
+2
source

How would I do this:

  • First you need to analyze this table. I suppose you can do it yourself; if not, google "regular expressions" are your friends.

  • The data structure you are working with is a classic tree . You need two arrays to work. First, this is an array of nodes, $nodes , where the keys are node identifiers, and the values ​​are node names and $links , where each key is the parent node, and each value is an array of children ( $links[$id][] = $suboff for each item would be enough).

  • Now you need to recursively lower the tree that you have. You enter a function with the following signature:

     function print_node( $nodeID, $level = 1 ) 

    This function should print the node itself (the information stored in $ nodes), with a dash of the fill level and call itself to display all the child nodes. They, in turn, will display all their trays, etc. You just need to call this function for top-level nodes.

+1
source

This class converts an array of flat categories into a structured array of trees:

 <?php /** * Creates a structured tree out of a flat category list */ class CategoryTree { /** * * @var array */ protected $categories = array(); /** * * @var array */ protected $tree = array(); /** * Default constructor * @param array $categories */ function __construct(array $categories) { $this->categories = $categories; } /** * Process a subtree * @param array $categories * @param integer $parentId * @return array */ protected function getSubtree(array $categories, $parentId = 0) { $tree = array(); foreach($categories as $category) { if($category['suboff'] == $parentId) { $tree[$category['id']] = $category; $tree[$category['id']]['children'] = $this->getSubtree($categories, $category['id']); } } return $tree; } /** * Get the category tree as structured array * @return array */ public function getTree() { if(empty($this->tree)) { $this->tree = $this->getSubtree($this->categories, 0); } return $this->tree; } /** * Get the category tree as string representation * @return string */ public function __toString() { return "<pre>" . print_r($this->getTree(), true) . "</pre>"; } } // Now, use the class with the givven data: $categories = array( array( 'id' => 1, 'category' => 'software', 'suboff' => 0 ), array( 'id' => 2, 'category' => 'programming', 'suboff' => 1 ), array( 'id' => 3, 'category' => 'Testing', 'suboff' => 1 ), array( 'id' => 4, 'category' => 'Designing', 'suboff' => 1 ), array( 'id' => 5, 'category' => 'Hospital', 'suboff' => 0 ), array( 'id' => 6, 'category' => 'Doctor', 'suboff' => 5 ), array( 'id' => 7, 'category' => 'Nurses', 'suboff' => 5 ), array( 'id' => 9, 'category' => 'Teaching', 'suboff' => 0 ), array( 'id' => 10, 'category' => 'php programming', 'suboff' => 2 ), array( 'id' => 11, 'category' => '.net programming', 'suboff' => 2 ) ); $myTree = new CategoryTree($categories); echo $myTree; ?> 
+1
source

IMHO logic:

  • Get all root elements (software, hospital, etc.)
  • Foreach root accepts a subelement (for software you will be programming, testing, and designing).
  • Add a subitem as a submachine
  • Loop recursively in subarray (s) you just add
0
source

You want to read the entire table in memory and turn it into a tree, where each node can be identified with its corresponding identifier number. Then pre-traverse the tree to print it.

0
source

In PHP wenn, I get data from a database:

 "SELECT* FROM Table WHERE suboff LIKE 0" foreach(item..) "SELECT* FROM Table WHERE suboff LIKE item.ID" foreach(item2..) $result[item][item2] 
0
source

Here is another approach that you need to understand very easily. This requires the table to be ordered using suboff , i.e.

 SELECT * FROM table ORDER BY suboff 

Assuming the result is stored in $table , you can use this very compressed PHP code:

 // this will hold the result $tree = array(); // used to find an entry using its id $lookup = array(); foreach($table as $row){ if($row['suboff'] === 0){ // this has no parent, add it at base level $tree[$row['category']] = array(); // store a reference $lookup[$row['id']] =& $tree[$row['category']]; }else{ // find the right parent, add the category $lookup[$row['suboff']][$row['category']] = array(); // store a reference $lookup[$row['id']] =& $lookup[$row['suboff']][$row['category']]; } } 
0
source

This solution is great for me.

 $array = array( array('1','software','0'), array('2','programming','1'), array('3','Testing','1'), array('4','Designing','1'), array('5','Hospital','0'), array('6','Doctor','5'), array('7','Nurses','5'), array('9','Teaching','0'), array('10','php programming','2'), array('11','.net programming','2') ); $newArray = getTree($array); function getTree( $rows, $suboff = 0) { $return = array(); foreach($rows as $row) { if($row[2] == $suboff){ $newrow = $row; $subs = $this->getTree($rows, $row[0]); if ( !empty($subs) ) { $newrow['subs'] = $subs; } $return[] = $newrow; } } return $return; } 
0
source

This is what I just wrote for my application and it works like a charm :)

 $array = [ 'i' => ['key' => 'i', 'name' => 'php programming', 'parent' => 'b'], 'g' => ['key' => 'g', 'name' => 'Nurses', 'parent' => 'e'], 'j' => ['key' => 'j', 'name' => '.net programming', 'parent' => 'b'], 'b' => ['key' => 'b', 'name' => 'programming', 'parent' => 'a'], 'a' => ['key' => 'a', 'name' => 'software', 'parent' => 'asd'], 'c' => ['key' => 'c', 'name' => 'Testing', 'parent' => 'a'], 'd' => ['key' => 'd', 'name' => 'Designing', 'parent' => 'a'], 'e' => ['key' => 'e', 'name' => 'Hospital', 'parent' => 'asd'], 'f' => ['key' => 'f', 'name' => 'Doctor', 'parent' => 'e'], 'h' => ['key' => 'h', 'name' => 'Teaching'], ]; function getAsTree(array &$array) { foreach ($array as $key => $item) { if (isset($item['parent']) && isset($array[$item['parent']])) { $array[$item['parent']]['children'][] = $item; unset($array[$key]); return getAsTree($array); } } return $array; } 

And here is the result:

 --- a: software ------ b: programming --------- i: php programming --------- j: .net programming ------ c: Testing ------ d: Designing --- e: Hospital ------ g: Nurses ------ f: Doctor --- h: Teaching 
0
source

All Articles