Skip to content

Instantly share code, notes, and snippets.

@prodhan
Created October 6, 2020 18:01
Show Gist options
  • Save prodhan/585f6cd6dd38247818a8dacc4eb8eab4 to your computer and use it in GitHub Desktop.
Save prodhan/585f6cd6dd38247818a8dacc4eb8eab4 to your computer and use it in GitHub Desktop.
<?php
/* Q1: Suppose this array come from back-end. data of this array can be dynamic.
You have to make a Dynamic HTML Output (using ul tag) based on this array,
where each item will fall under its parent id.
output will look something like this.
Bangladesh
Dhaka
Uttara
Khilgaon
Noyakhali
Maijdi
Canada
Torrento
*/
$arr = [
[
"id" => 500,
"p_id" => 0,
"title" => "Bangladesh"
],
[
"id" => 510,
"p_id" => 500,
"title" => "Dhaka"
],
[
"id" => 511,
"p_id" => 510,
"title" => "Uttara"
],
[
"id" => 512,
"p_id" => 510,
"title" => "Khailgaon"
],
[
"id" => 513,
"p_id" => 500,
"title" => "NoyaKhali"
],
[
"id" => 514,
"p_id" => 513,
"title" => "Maijdi"
],
[
"id" => 515,
"p_id" => 0,
"title" => "Canada"
],
[
"id" => 516,
"p_id" => 515,
"title" => "Toronto"
],
];
foreach($arr as $a){
if($a['p_id']===0){
echo "<ul>";
echo "<li>".$a['title'];
foreach($arr as $b){
if($b['p_id']===$a['id']){
echo "<ul>";
echo "<li>".$b['title'];
foreach($arr as $c){
if($c['p_id']===$b['id']){
echo "<ul>";
echo "<li>".$c['title'];
echo "</li>";
echo "</ul>";
}
}
echo "</li>";
echo "</ul>";
}
}
echo "</li>";
echo "</ul>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment