i have an array like this
Array
(
[0] => Array
(
[name] => Region
[id] => 3
[parent_id] => 2
[children] => Array
(
[0] => Array
(
[name] => Asia
[id] => 4
[parent_id] => 3
[children] => Array
(
[0] => Array
(
[name] => Central Asia
[id] => 6621
[parent_id] => 4
[children] => Array
(
[0] => Array
(
[name] => Afghanistan
[id] => 5
[parent_id] => 6621
[children] => Array
(
[0] => Array
(
[name] => Balkh
[id] => 6
[parent_id] => 5
[children] => Array
(
[0] => Array
(
[name] => Mazar-e-Sharif
[id] => 7
[parent_id] => 6
)
)
)
[1] => Array
(
[name] => Kabol
[id] => 10
[parent_id] => 5
)
[2] => Array
(
[name] => Qandahar
[id] => 12
[parent_id] => 5
)
)
)
)
)
[1] => Array
(
[name] => Middle East
[id] => 6625
[parent_id] => 4
[children] => Array
(
[0] => Array
(
[name] => Armenia
[id] => 14
[parent_id] => 6625
)
)
)
)
)
)
)
)
now i want to convert this array in to ul-li
in tree formate
but it is giving me weird output
for example Region
i want like this
<li id=3 parent_id=2 > Region </li>
here i want use id
and parent_id
as attribute
php function is
function olLiTree($tree)
{
echo '<ul>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<li>', $key;
olLiTree($item);
echo '</li>';
} else {
echo '<li>', $item, '</li>';
}
}
echo '</ul>';
}
output for region is like this from above function
<ul>
<li>0
<ul>
<li>Region</li>
<li>3</li>
<li>2</li>
<li>children
<ul>
Perhaps this is recursion you seek.
function olLiTree( $tree ) {
echo '<ul>';
foreach ( $tree as $item ) {
echo "<li id=\"$item[id]\" parent_id=\"$item[parent_id]\" > $item[name] </li>";
if ( isset( $item['children'] ) ) {
olLiTree( $item['children'] );
}
}
echo '</ul>';
}
I think this one is correct:
function olLiTree($tree) {
echo "<ul>";
foreach ($tree as $v) {
echo "<li id='{$v['id']}' parent_id='{$v['parent_id']}'>{$v['name']}</li>";
if ($v['children'])
olLiTree($v['children']);
}
echo "</ul>";
}
Output:
Region
Asia
Central Asia
Afghanistan
Middle EastBalkh
Mazar-e-Sharif
KabolQandaharArmenia
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With