Save Tree array in mysql - php

Array
(
[Root] => Array
(
[Parent0] => Array
(
[Child0] => Child0
)
[Parent1] => Array
(
[Child1] => Child1
)
)
)
Above tree array need to be save in mysql with parent id so results should be like below:
id parent_id name
1 0 Root
2 1 Parent0
3 2 Child0
4 1 Parent1
5 4 Child1
Any one please let me know how can i save above results in mysql using php.
Thanks in advance for quick response.

Try this:EDITED
$c=0;
$x;
foreach($array1 as $key=>$val){
if(is_array($val)){
echo "insert $key with parent id $c<br>";
$c++;
$x=$c;
foreach($val as $key1=>$val1){
echo " insert $key1 with parent id $x<br>";
$c++;
if(is_array($val1)){
foreach($val1 as $key2=>$val2){
echo "insert $key2 with parent id $c<br>";
$c++;
getlevel($val2,$c);
}
}/* else{
echo "else insert $key1 with parent id $c<br>";
$c++; */
}
}
}
function getlevel($value,$c1){
if(is_array($value)){
foreach($value as $keyV=>$Value){
echo " insert $keyV with parent id $c1<br>";
$c1++;
if(is_array($Value)){
getlevel($Value,$c1);
}
}
}
}
where ever i have written echo replace with your sql.Hope it helps.here $array is your array.

Below the perfect working script in any depth level tree.
$root_id;
$parent_id = 0;
foreach ( $tree_array as $root_key => $root_value ) {
$parent_id = insertRecord($root_key, $parent_id);
$root_id = $parent_id;
if ( is_array($root_value) ) {
foreach ( $root_value as $parent_key => $parent_value ) {
$parent_id = insertRecord($parent_key, $root_id);
$keep_parent_id = $parent_id;
if ( is_array($parent_value) ) {
foreach ( $parent_value as $child_key => $child_value ) {
$parent_id = insertRecord($child_key, $keep_parent_id);
getlevel($child_value, $parent_id);
}
}
}
}
}
function getlevel($sub_childs, $new_parent_id) {
$keep_new_parent_id = $new_parent_id;
if ( is_array($sub_childs) ) {
foreach ( $sub_childs as $sub_child => $sub_child_sub ) {
$new_parent_id = insertRecord($sub_child, $keep_new_parent_id);
if ( is_array($sub_child_sub) ) {
getlevel($sub_child_sub, $new_parent_id);
}
}
}
}
function insertRecord($name, $parent_id) {
$q = "insert into xtable set name = '".$name."', parent_id = '".$parent_id."'";
mysql_query($q);
$folder_id = mysql_insert_id();
return $folder_id;
}
Thanks to everyone for your efforts.

If you want to achieve parent child tree you can go for the below code with n depth
Automobile
Fuel
Gasoline
Diesel
Maintenance
Food
Fish
Pork
First create a database table named “categories” that has fields.
- category_id (PK int)
- parent_id (int)
- title (varchar)
<?php
$connect = mysql_connect("localhost", "root", "") or die ( mysql_error() );
mysql_select_db("test");
$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `category_id`") or die( mysql_error() );
$tree = ""; // Clear the directory tree
$depth = 1; // Child level depth.
$top_level_on = 1; // What top-level category are we on?
$exclude = array(); // Define the exclusion array
array_push($exclude, 0); // Put a starting value in it
while ( $nav_row = mysql_fetch_array($nav_query) )
{
$goOn = 1; // Resets variable to allow us to continue building out the tree.
for($x = 0; $x < count($exclude); $x++ ) // Check to see if the new item has been used
{
if ( $exclude[$x] == $nav_row['category_id'] )
{
$goOn = 0;
break; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
}
}
if ( $goOn == 1 )
{
$tree .= $nav_row['title'] . "<br>"; // Process the main tree node
array_push($exclude, $nav_row['category_id']); // Add to the exclusion list
if ( $nav_row['category_id'] < 6 )
{ $top_level_on = $nav_row['category_id']; }
$tree .= build_child($nav_row['category_id']); // Start the recursive function of building the child tree
}
}
function build_child($oldID) // Recursive function to get all of the children...unlimited depth
{
global $exclude, $depth; // Refer to the global array defined at the top of this script
$tempTree = "";
$child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
while ( $child = mysql_fetch_array($child_query) )
{
if ( $child['category_id'] != $child['parent_id'] )
{
for ( $c=0;$c<$depth;$c++ ) // Indent over so that there is distinction between levels
{ $tempTree .= " "; }
$tempTree .= "- " . $child['title'] . "<br>";
$depth++; // Incriment depth b/c we're building this child's child tree (complicated yet???)
$tempTree .= build_child($child['category_id']); // Add to the temporary local tree
$depth--; // Decrement depth b/c we're done building the child's child tree.
array_push($exclude, $child['category_id']); // Add the item to the exclusion list
}
}
return $tempTree; // Return the entire child tree
}
echo $tree;
?>
You can copy paste the above code and you are done :)

Related

Make HTML table from array returned from execute_db in PHP - entries duplicated

I want to populate a html table from the results of a SQL query, the fields included will vary depending on choices the user makes so I want to autmatically set the headings etc based on what is in the results of the query. I found the array_to_table function on the website https://inkplant.com/code/array-to-table and it does what I want except the data is duplicated:-
Expected result
Formation Play
A SW
S DL
Actual Result
Formation 0 Play 1
A A SW SW
S S DL DL
I think it may be be to do with the type of array I'm creating but I'm unsure how to alter the code to generate my expected result. I'm not sure if I should create the array in a different way or whether (or how) I should change the function to work with the type of array I have.
#SQL for creating example table
CREATE TABLE `example` ( `id` INT NOT NULL AUTO_INCREMENT , `form` VARCHAR(10) NOT NULL , `playcall` VARCHAR(10) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
#Sample data
INSERT INTO `example` (`id`, `form`, `playcall`) VALUES (NULL, 'A', 'SW'), (NULL, 'S', 'DL');
#mycode
$sql = "SELECT `form` as 'Formation',`playcall` as 'Playcall' FROM `example` ORDER BY `form` DESC";
$res = execute_db($sql3 $conn);
$caption = "Example table";
echo array_to_table($res,$caption);
#function
function array_to_table($data,$caption,$args=false) {
if (!is_array($args)) { $args = array(); }
foreach (array('class','column_widths','custom_headers','format_functions','nowrap_head','nowrap_body','capitalize_headers') as $key) {
if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; }
}
if ($class) { $class = ' class="'.$class.'"'; } else { $class = ''; }
if (!is_array($column_widths)) { $column_widths = array(); }
//get rid of headers row, if it exists (headers should exist as keys)
if (array_key_exists('headers',$data)) { unset($data['headers']); }
$t="<table style='width:40%' class='w3-table w3-striped w3-bordered'>";
$t .= $caption;
$i = 0;
foreach ($data as $row) {
$i++;
//display headers
if ($i == 1) {
foreach ($row as $key => $value) {
if (array_key_exists($key,$column_widths)) { $style = ' style="width:'.$column_widths[$key].'px;"'; } else { $style = ''; }
$t .= '<col'.$style.' />';
}
$t .= '<thead><tr>';
foreach ($row as $key => $value) {
if (is_array($custom_headers) && array_key_exists($key,$custom_headers) && ($custom_headers[$key])) { $header = $custom_headers[$key]; }
elseif ($capitalize_headers) { $header = ucwords($key); }
else { $header = $key; }
if ($nowrap_head) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
$t .= '<td'.$nowrap.'>'.$header.'</td>';
}
$t .= '</tr></thead>';
}
//display values
if ($i == 1) { $t .= '<tbody>'; }
$t .= '<tr>';
foreach ($row as $key => $value) {
if (is_array($format_functions) && array_key_exists($key,$format_functions) && ($format_functions[$key])) {
$function = $format_functions[$key];
if (!function_exists($function)) { custom_die('Data format function does not exist: '.htmlspecialchars($function)); }
$value = $function($value);
}
if ($nowrap_body) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
$t .= '<td'.$nowrap.'>'.$value.'</td>';
}
$t .= '</tr>';
}
$t .= '</tbody>';
$t .= '</table>';
return $t;
}
EDIT: Based on the tip from https://stackoverflow.com/users/13851118/dhnwebpro I dumped the array to see what it contained:-
Array
(
[0] => Array
(
[Formation] => A
[0] => A
[Playcall] => SW
[1] => Sw
)
[1] => Array
(
[Formation] => S
[0] => S
[Playcall] => DL
[1] => DL
)
)
EDIT2: I changed the format of the query and got it working:-
$res3 = $conn->query($sql3)->fetchAll(PDO::FETCH_ASSOC);
Fetch both was indeed the default and I was able to override that with the above statement.
As #dhnwebpro said PDO was defaulting to PDO::FETCH_BOTH so I overrode it by changing the execution to:-
$res3 = $conn->query($sql3)->fetchAll(PDO::FETCH_ASSOC);

How can I convert a hierarchical tree to parent-child relationships?

At the moment, i'm creating a dynamic menu for my own CMS (practising) in PHP, but I don't know to save the data in my database.
Database structure:
menuitem_id
menu_id
menuitem_order
menuitem_name
menuitem_page_id
parent_menuitem_id
I do get this output as a hierarchical tree, but that isn't the desired format for storing it into my database:
Array
(
[0] => Array
(
[id] => 2
)
[1] => Array
(
[id] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[children] => Array
(
[0] => Array
(
[id] => 4
)
[1] => Array
(
[id] => 5
)
)
)
[1] => Array
(
[id] => 6
)
)
)
)
However, I want to convert this to a parent ID array with new fresh ID's (I will truncate the table and insert new data). Something like this:
Array
(
[0] => 0
[1] => 0
[2] => 2
[3] => 3
[4] => 3
[5] => 2
)
How can this be done?
Note: i have read this article, but I need the opposite code of it.
You need a recursive function:
function flattenHierarchicalArray($arr, $parentId = null) {
$items = array();
foreach ($arr as $item) {
$items[] = array('id' => $item['id'], 'parentId' = $parentId);
if (isset($item['children'])) $items = array_merge($items, flattenHierarchicalArray($item['children'], $item['id']));
}
return $items;
}
I think I have the solution combined with AlliterativeAlice's PHP code.
I'm using the Nestable plugin. That extension creates my hierarchical tree and sets it in a hidden field in my form (done by JavaScript). I updated this code to create new IDs by adding this code:
var nestable_update = function(e){
//added for updating old IDs
$(".dd-item").each(function(index){
$(this).data("id", index+1);
});
var list = e.length ? e : $(e.target),
output = list.data("output");
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable("serialize")));
} else {
output.val("JSON browser support required for this demo.");
}
};
$(".dd").nestable({
maxDepth:5
}).on("change", nestable_update);
nestable_update($(".dd").data("output", $("#nestable_output")));
I used your PHP code for getting the parentID (many thanks to AlliterativeAlice, because it's more efficient than my original PHP code):
function flatten_hierarchical_tree($arr, $parent_id=0) {
$items = array();
foreach ($arr as $item) {
$items[] = array('id' => $item['id'], 'parent_id' => $parent_id);
if (isset($item['children'])) $items = array_merge($items, flatten_hierarchical_tree($item['children'], $item['id']));
}
return $items;
}
For those who are interested in my final code. It works for storing the data in the database and build it again into a hierarchical tree + a printable tree for HTML.
JavaScript code for the nestable plugin:
var nestable_update = function(e){
$(".dd-item").each(function(index){
$(this).data("id", index+1);
});
var list = e.length ? e : $(e.target),
output = list.data("output");
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable("serialize")));
} else {
output.val("JSON browser support required for this demo.");
}
};
$(".dd").nestable({
maxDepth:5
}).on("change", nestable_update);
nestable_update($(".dd").data("output", $("#nestable_output")));
Database structure:
menuitem_id
menu_id
menuitem_order
menuitem_name
menuitem_page_id
parent_menuitem_id
PHP functions for building trees (format storing data in database + format getting data from database):
function create_flatten_hierarchical_tree($tree, $parent_id=0) {
$items = array();
foreach ($tree as $item) {
$items[] = array("id" => $item["id"], "parent_id" => $parent_id);
if (isset($item["children"])) $items = array_merge($items, create_flatten_hierarchical_tree($item["children"], $item["id"]));
}
return $items;
}
function create_hierarchical_tree($tree, $root=0) {
$return = array();
foreach($tree as $child => $parent) {
if($parent["parent_menuitem_id"] == $root) {
if(isset($tree[$child]["menuitem_id"]) === true){
$parent['children'] = create_hierarchical_tree($tree, $tree[$child]["menuitem_id"]);
}
unset($tree[$child]);
$return[] = $parent;
}
}
return empty($return) ? null : $return;
}
function print_hierarchical_tree($tree, $rows_pages) {
if(!is_null($tree) && count($tree) > 0) {
$return .= "<ol class='dd-list'>";
foreach($tree as $item){
$options = "";
foreach($rows_pages as $row_pages){
$selected = "";
if($row_pages["page_id"] == $item["menuitem_page_id"]){
$selected = "selected";
}
$options .= "<option value='".$row_pages["page_id"]."' $selected>".$row_pages["friendly_url"]."</option>";
}
$return .= "<li class='dd-item' data-id='".$item["menuitem_id"]."'><div class='dd-handle'>drag</div><div class='item_wrapper'><div class='item'><div class='item_title'>".$item["menuitem_name"]."</div></div><div class='item_sub'><div class='label_input'><label for='menuitem_name".$item["menuitem_id"]."'>Menuitem name</label><input type='text' id='menuitem_name".$item["menuitem_id"]."' name='menuitem_name[]' value='".$item["menuitem_name"]."' /></div><div class='label_input'><label for='page_link".$item["menuitem_id"]."'>Page link</label><label class='select'><select id='page_link".$item["menuitem_id"]."' name='menuitem_page_id[]'>".$options."</select></label></div> <a onClick='delete_menuitem(".$item["menuitem_id"].");' class='button red_bg delete'>Delete</a></div></div>";
$return .= print_hierarchical_tree($item["children"], $rows_pages);
$return .= "</li>";
}
$return .= "</ol>";
}
return empty($return) ? null : $return;
}
Core code of menu_edit.php page:
<?php
$stmt_menuitems = $dbh->prepare("SELECT * FROM inno_mw_thurs_menuitems mi WHERE mi.menu_id=:menu_id");
$stmt_menuitems->bindParam(":menu_id", $_GET["menu_id"]);
$stmt_menuitems->execute();
if (!empty($stmt_menuitems->rowCount())) {
?>
<div class="dd">
<?php
$result = $stmt_menuitems->fetchAll();
$tree = create_hierarchical_tree($result);
$stmt_pages = $dbh->prepare("SELECT * FROM inno_mw_thurs_pages");
$stmt_pages->execute();
$rows_pages = $stmt_pages->fetchAll();
$tree = print_hierarchical_tree($tree, $rows_pages);
echo $tree;
?>
</div>
<?php
}
Core code of menu_edit_process.php page:
if(isset($_POST["menu_id"])){
$menu_id = $_POST["menu_id"];
$nestable_output = json_decode($_POST["nestable_output"], true);
$parent_menuitem_ids_arr = create_flatten_hierarchical_tree($nestable_output);
$stmt = $dbh->prepare("TRUNCATE TABLE inno_mw_thurs_menuitems");
$stmt->execute();
$stmt = $dbh->prepare("INSERT INTO inno_mw_thurs_menuitems (menu_id, menuitem_order, menuitem_name, menuitem_page_id, parent_menuitem_id) VALUES (:menu_id, :menuitem_order, :menuitem_name, :menuitem_page_id, :parent_menuitem_id)");
$menuitem_order_arr = array();
foreach($_POST["menuitem_name"] as $f => $name){
$menuitem_name = $_POST["menuitem_name"][$f];
$menuitem_page_id = $_POST["menuitem_page_id"][$f];
$parent_menuitem_id = $parent_menuitem_ids_arr[$f]["parent_id"];
if(array_key_exists($parent_menuitem_id, $menuitem_order_arr) && $parent_menuitem_id != 0){
$menuitem_order_arr[$parent_menuitem_id] += 1;
}
else{
$menuitem_order_arr[$parent_menuitem_id] = 0;
}
$stmt->bindParam(":menu_id", $menu_id);
$stmt->bindParam(":menuitem_order", $menuitem_order_arr[$parent_menuitem_id]);
$stmt->bindParam(":menuitem_name", $menuitem_name);
$stmt->bindParam(":menuitem_page_id", $menuitem_page_id);
$stmt->bindParam(":parent_menuitem_id", $parent_menuitem_id);
$stmt->execute();
}
header("location: menus_list.php");
}
Please, feel free to improve this code.

Category Hierarchy (PHP/MySQL) in Yii

I found this here: Category Hierarchy (PHP/MySQL)
And i want to display that code, but it is not working correctly.
I got the following Hierarchy:
-Airsoft
--Scopes
That's all. But the code is displaying:
-Airsoft
--Scopes (So far so good)
-Scopes <--- this one should not be here!
Here's the code:
public static function producten(){
$connection=Yii::app()->db; // assuming you have configured a "db" connection
$sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
$command=$connection->createCommand($sql);
$dataReader=$command->query();
$refs = array();
foreach ($dataReader as $row)
{
$ref = & $refs[$row['id']];
$ref['parent'] = $row['parent'];
$ref['naam'] = $row['naam'];
if ($row['parent'] == NULL)
{
$list[$row['id']] = & $ref;
}
else
{
$refs[$row['parent']]['children'][$row['id']] = & $ref;
}
}
function toUL(array $array)
{
$html = '<ul>' . PHP_EOL;
foreach ($array as $value)
{
$html .= '<li>' . $value['naam'];
if (!empty($value['children']))
{
$html .= toUL($value['children']);
}
$html .= '</li>' . PHP_EOL;
}
$html .= '</ul>' . PHP_EOL;
return $html;
}
print_r($refs);
echo toUL($refs);
}
The print_r() in there is displaying:
Array ( [1] => Array ( [parent] => [naam] => Airsoft [children] => Array ( [2] => Array ( [parent] => 1 [naam] => Scopes ) ) ) [2] => Array ( [parent] => 1 [naam] => Scopes ) )
Can somebody figure out what's wrong with the code and help me please?
You can try this:
$connection=Yii::app()->db; // assuming you have configured a "db" connection
$sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
function createList($elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent'] == $parentId) {
$children = createList($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$list = createList($dataReader);
CVarDumper::dump($list, 5678, true);

Find the top level parent

I have a MySQL table with id, category_id (parent id), and url.
I have a class that looks something like this. I have removed all unnecessary functions.
class categoriesBuilder
{
var $items = array();
var $html = array();
function fetch_assoc_all( $sql )
{
$result = mysql_query( $sql, $this->conn );
if ( !$result ){
return false;
}
$assoc_all = array();
while( $fetch = mysql_fetch_assoc( $result ) ){
$assoc_all[] = $fetch;
}
mysql_free_result( $result );
return $assoc_all;
}
function get_categories()
{
$sql = 'SELECT id, category_id, url FROM categories ORDER BY category_id, id;';
return $this->fetch_assoc_all( $sql );
}
function get_category_string($root_id=0)
{
$this->html = array();
$this->items = $this->get_categories();
foreach ( $this->items as $item )
$children[$item['category_id']][] = $item;
// loop will be false if the root has no children
$loop = !empty( $children[$root_id] );
// initializing $parent as the root
$parent = $root_id;
$parent_stack = array();
while ( $loop && ( ( $option = each( $children[$parent] ) ) || ( $parent > $root_id ) ) )
{
if ( $option === false )
{
$parent = array_pop( $parent_stack );
}
elseif ( !empty( $children[$option['value']['id']] ) )
{
array_push( $parent_stack, $option['value']['category_id'] );
$parent = $option['value']['id'];
// HTML for menu item containing childrens (open)
$this->html[] = $option['value']['url'] . "/";
}
else
{
$this->html[] = $option['value']['url'] . "/";
}
}
return implode($this->html );
}
}
I need a function that returns only the top level parent. there may be several sub categories.
i.e.
category id 1
category id 3
category id 4
category id 5
category id 2
category id 6
In this example if i entered 3, 4 or 5 into the function the output would be 1. if i entered 6 i would get 2.
I also need a similar function that shows all parent folders.
for example if i entered 3 i would get 1 but if i entered 4 or 5 i would get 1-3
Thanks for your help.
Assuming your DB is like this:
(1, 0, URL1),
(3, 1, URL3),
(4, 3, URL4),
(5, 3, URL5),
(2, 0, URL2),
(6, 2, URL6)
Then you just need to walk up the list
e.g.
function get_top_parent($category_id, $root_id=0)
{
// Grab the id's and category's
$item_list = array();
foreach($this->items as $item) {
$item_list[$item['id']] = $item['category_id'];
}
$current_category = $category_id;
while(TRUE) {
if ($item_list[$current_category] == $root_id) {
// Check to see if we have found the parent category.
return $current_category;
} else {
// update our current category
$current_category = $item_list[$current_category];
}
}
}
function get_parents($category_id, $root_id=0)
{
$parents = array();
// Grab the id's and category's
$item_list = array();
foreach($this->items as $item) {
$item_list[$item['id']] = $item['category_id'];
}
$current_category = $category_id;
while(TRUE) {
// Check to see if we have found the root category.
if ($item_list[$current_category] == $root_id) {
return $parents;
} else {
// update our current category and parents
$current_category = $item_list[$current_category];
array_unshift($parents, $current_category);
}
}
}
reworked to return URL (I did not verify this code but it should work):
function get_top_parent($category_id, $root_id=0)
{
// Grab the id's and category's
$item_list = array();
foreach($this->items as $item) {
$item_list[$item['id']] = array(
'category_id' => $item['category_id'],
'url' => $item['url']
);
}
$current_category = $category_id;
while(TRUE) {
if ($item_list[$current_category]['category_id'] == $root_id) {
// Check to see if we have found the parent category.
return $item_list[$current_category]['url'];
} else {
// update our current category
$current_category = $item_list[$current_category]['category_id'];
}
}
}
function get_parents($category_id, $root_id=0)
{
$parents = array();
// Grab the id's and category's
$item_list = array();
foreach($this->items as $item) {
$item_list[$item['id']] = array(
'category_id' => $item['category_id'],
'url' => $item['url']
);
}
$current_category = $category_id;
while(TRUE) {
// Check to see if we have found the root category.
if ($item_list[$current_category]['category_id'] == $root_id) {
return $parents;
} else {
$temp_array = array(
'category_id' => $current_category
'url' => $item_list[$current_category]['url']
);
// update our current category and parents
$current_category = $item_list[$current_category]['category_id'];
array_unshift($parents, $temp_array);
}
}
}
The first function returns the URL, the second function should return an array of arrays... You will have the standard index, with "category_id" and "url" as nested/sub arrays... (If in doubt, just do a print_r of the return value to see what I mean)
again, i checkced the origional code but not the update...

Parent child Relationship in mysql

I am having a table like the following,need to display as Parent and child format
--------------------------------------------------------
id role_name role_id parent_id
--------------------------------------------------------
1 NSM 1 0
2 MR 5 2
3 ASM 4 3
4 ZSM 3 4
5 RSM 2 1
---------------------------------------------------------
the result is like to be the following
NSM
---RSM
-----ZSM
-----NSM
-----MR
NSM->ROOT
RSM->FIRST CHILD
ZSM->SECOND CHILD
NSM->THIRD CHILD
MR->LEAF
// Fetch all the roles
$result = mysql_query("select * from roles");
$roles = array();
while( $role = mysql_fetch_assoc($result) ) {
$roles[] = $role;
}
// Function that builds a tree
function build_tree($roles, $parent_id=0) {
$tree = array();
foreach ($roles as $role) {
if ($role['parent_id'] == $parent_id) {
$tree[] = array(
'role' => $role,
'children' => build_tree($roles, $role['parent_id'])
);
}
}
return $tree;
}
// Function that walks and outputs the tree
function print_tree($tree) {
if (count($tree) > 0) {
print("<ul>");
foreach($node in $tree) {
print("<li>");
htmlspecialchars($node['role']['role_name']);
print_tree($node['children']);
print("</li>");
}
print("</ul>");
}
}
SQL Results are always flat - you'll not be able to return a hierarchy view of that data in a query.
Instead, I would suggest using whichever client components you are using to show that (is it a tree? what exactly?) that knows how to go thru a flat list and build a hierarchy out of that.
If you want to print a view like that in a console (why would you ever want to do that?), you could do like this:
$data = array();
$query = mysql_query("SELECT * FROM table ORDER BY parent_id");
while($array = mysql_fetch_assoc($query))
{
$data[$array['parent_id']][] = $array;
}
function output_hierarchy($id, $prepend)
{
$current = $data[$id];
foreach($current as $item)
{
print $prepend . " " . $item['role_name'];
if(count($data[$item['id']]) > 0)
{
output_hierarchy($item['id'], $prepend . "--");
}
}
}
output_hierarchy(0, '');
If you want to use this on your website, you can easily adapt it. Code should be self-explanatory.

Categories