0
I have an array like this:
Array
(
[38] => Array
(
[name] => Categoria Raiz 1
[link] => https://...
[id_parent] => 0
)
[205] => Array
(
[name] => Subcategoria 1
[link] => https://...
[id_parent] => 38
)
[206] => Array
(
[name] => Subcategoria 2
[link] => https://...
[id_parent] => 38
)
[484] => Array
(
[name] => Categoria Raiz 2
[link] => https://...
[id_parent] => 0
)
[485] => Array
(
[name] => Subcategoria 3
[link] => https://...
[id_parent] => 484
)
[39] => Array
(
[name] => categoria Raiz 3
[link] => https://...
[id_parent] => 0
)
[147] => Array
(
[name] => Subcategoria 4
[link] => https://...
[id_parent] => 39
)
)
Indexes are the category Ids.
I need to nest the root categories with their subcategories to create a dropdown menu, but I’m missing the logic.
I’m using the template engine Smarty
, but I’ll write down what I’ve done in PHP
pure to facilitate.
<?php
foreach($array as $key => $value) { ?>
<li data-id_parent="<?php echo $value['id_parent']; ?>">
<a href="<?php echo $value['link']; ?>"><?php echo $value['name']; ?></a>
<?php
if (!isset($id_anterior)) { ?>
<ul>
<?php } else {
if ($id_anterior != $value['id_parent']) { ?>
</ul>
<ul>
<?php }
}
?>
</li>
<?php
$id_anterior = $key;
}
?>
I wish the way out was something like this:
<li data-id_parent="0">
<a href="https://...">Categoria Raiz 1</a>
<ul>
<li data-id_parent="38">
<a href="https://...">Subcategoria 1</a>
</li>
<li data-id_parent="38">
<a href="https://...">Subcategoria 2</a>
</li>
</ul>
</li>
<li data-id_parent="0">
<a href="https://...">Categoria Raiz 2</a>
<ul>
<li data-id_parent="484">
<a href="https://...">Subcategoria 3</a>
</li>
</ul>
</li>
<li data-id_parent="0">
<a href="https://...">Categoria Raiz 3</a>
<ul>
<li data-id_parent="39">
<a href="https://...">Subcategoria 4</a>
</li>
</ul>
</li>
Where am I going wrong?
how is the table?
– Diego Ananias
@Hananiamizrahi The table consists of columns with the same names as the keys of the array, the column being
id
primary key and columnid_parent
foreign key referencing the table itself.– Caesar