UPDATED with an exact working example.
Your topic is something I am also struggling with. It has a title "multidimensional arrays" in association with mysql or mysqli.
Step 1: THE DB ..
CREATE TABLE `tbl_categories` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_bin NOT NULL DEFAULT '0',
`parent_id` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `tbl_categories` (`id`, `name`, `parent_id`) VALUES
(1, 'element1', 0),
(2, 'element2', 1),
(3, 'element3', 2),
(4, 'element4', 3);
As You see the parent_id is all you need to change in an item to change the hierarchy.
Step 2:
A function to iterate through the entries...
function categoryParentChildTree($parent = 0, $category_tree_array = '') {
global $dbConnection;
$parent = $dbConnection->real_escape_string($parent);
if (!is_array($category_tree_array)) //###
$category_tree_array = array();
$sqlCategory = "SELECT id,name,parent_id FROM tbl_categories WHERE parent_id = $parent ORDER BY id ASC";
$resCategory=$dbConnection->query($sqlCategory);
if ($resCategory->num_rows > 0) {
while($rowCategories = $resCategory->fetch_assoc()) {
$category_tree_array[] = array("id" => "<div id='".$rowCategories['id']."'", "name" => " data-name='".$rowCategories['name']."'>{$rowCategories['name']}");
$category_tree_array = categoryParentChildTree($rowCategories['id'], $category_tree_array);
}
}
return $category_tree_array;
}
STEP 3 : Using the function
$categoryList = categoryParentChildTree();
foreach($categoryList as $key => $value){
echo $value['id']." ".$value['name'];
}
The very important line here is the one I marked with ###. The aregument there is to check wether the passed variable is an array.In case it is not, the function continues. In case it is an array, the function calls itself on that same variable to flatten it and turn it into a variable in the process.
The output of this whole thing is as follows:
<html>
<head>
</head>
<body>
<div id="1" data-name="element1">element1
<div id="2" data-name="element2">element2
<div id="3" data-name="element3">element3
<div id="4" data-name="element4">element4
</div>
</div>
</div>
</div>
</body>
</html>
Theoretically this deals with infinite levels of nesting and items. I hope it helps.
This is based on a tutorial by Saurabh Kumar Singh. You can see the fully functional original demo and the downloadable zip from the link:
http://demo.stepblogging.com/category-tree/
Finally if this addresses your needs please don't forget to accept the answer.