I have a table named organization like below
id departmentName parentId
1 ABC Company Ptd Ltd 0
2 IT Department 1
3 Procurement Dept 1
4 Invoicing Team 3
5 Credit Control Team 3
6 Human Resource Dept 1
The row with id 1 will never be deleted and always have 0 as parentId (which acts as root)
How can I loop this correctly relating each to their respective parent or subordinates?
I made this way but no success yet
$result = mysqli_query($con,"SELECT * FROM organization WHERE id=1");
while($row = mysqli_fetch_array($result))
echo "<ul>";
{
?>
<li><?php echo $row['departmentName'];?><li>
<ul>
<?php
$result2 = mysqli_query($con,"SELECT * FROM organization WHERE parentId=$row[id]");
while($row2 = mysqli_fetch_array($result2))
{
?>
<li><?php echo $row2['departmentName'];?>
<ul>
<li><?php echo $row2['departmentName'];?></li>
<li><?php echo $row2['departmentName'];?></li>
</ul>
</li>
<?php
}
?>
</ul>
<?php
}
?>
The idea is it has to output as a clean unordered list for each
Your kind help is appreciated
Thank you
After getting the values, you need to group them first, you also might to make a recursion function and then echo the list. Consider this example:
$con = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($con, 'SELECT * FROM `organization`');
$fetched_array = array();
while($row = $result->fetch_assoc()) {
$fetched_array[] = $row;
}
// // nest first the array
function build_array($array, $parentId = 0) {
$values = array();
foreach($array as $value) {
if($value['parentId'] == $parentId) {
$child = build_array($array, $value['id']);
if($child) {
$value['children'] = $child;
}
$values[] = $value;
}
}
return $values;
}
$formatted_values = build_array($fetched_array);
// format them into ul li
function build_list($array) {
$list = '<ul>';
foreach($array as $key => $value) {
foreach($value as $key => $index) {
if(is_array($index)) {
$list .= build_list($index);
} else {
if(!is_numeric($index)) {
$list .= "<li>$index</li>";
}
}
}
}
$list .= '</ul>';
return $list;
}
echo build_list($formatted_values);
Should echo to something like:
<ul>
<li>ABC Company Ptd Ltd</li>
<li>
<ul>
<li>IT Department</li>
<li>Procurement Dept</li>
<li>
<ul>
<li>Invoicing Team</li>
<li>Credit Control Team</li>
</ul>
</li>
<li>Human Resource Dept</li>
</ul>
</li>
</ul>