Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort flat array into multidimensional 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 a code to get all these information in a multidimensional array based on the suboff as follows,

-software
--programming
---php programming
--- .net programming
--testing
--designing
-hospital 
--doctor
--nurses
-teaching
like image 506
Sunil Kumar P Avatar asked Feb 22 '23 15:02

Sunil Kumar P


1 Answers

Assuming MySQL as 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 a job like this.

like image 68
DaveRandom Avatar answered Mar 07 '23 23:03

DaveRandom