Forum Moderators: coopster
It's been a while since i have posted anything.
I am looking for a solution with the following.
I have a multi-dimensional array and it consits of a single level of 'categories', i would like to loop through the parents e.g. id_parent = 0 and then pull all the children in afterwards in my template files.
To make things a little clearer, i will explain how i would do it in pure php.
So i have an array, like follows:
Array (
[1] = Array(
[id] => 1,
[title] => 'Parent Cat',
[id_parent] = 0
),
[2] = Array(
[id] => 2,
[title] => 'Parent Cat 2',
[id_parent] = 0
)
[2] = Array(
[id] => 3,
[title] => 'Child Cat 1',
[id_parent] = 1
)
[2] = Array(
[id] => 4,
[title] => 'Child Cat 2',
[id_parent] = 1
)
[2] = Array(
[id] => 5,
[title] => 'Child Cat 3',
[id_parent] = 2
)
)
So, with this array i would like to output the following
Parent cat 1
- child cat 1
- child cat 2
Parent cat 2
- child cat 3
So, i would like to do a nested foreach loop like so ...
{foreach item="category" from="$categories"}
<li><a href="categories/{$category.id}">{$category.title}</a> ({$category.products})</li>{foreach item="subcategory" from="$categories[$category.id]"}
<li><a href="categories/{$subcategory.id}">{$subcategory.title}</a> ({$subcategory.products})</li>{/foreach}
{/foreach}
The code above doesn't work, because it's mainly pseudo code, if someone could help me out with the logic then i would be truly grateful.
Thank you all for your time.
<?php
$myjunk[1] = array('id' => '1', 'title' => 'Parent Cat', 'id_parent' => '0' );
$myjunk[2] = array('id' => '2', 'title' => 'Parent Cat 2', 'id_parent' => '0');
$myjunk[3] = array('id' => '3', 'title' => 'Child Cat 1', 'id_parent' => '1' );
$myjunk[4] = array('id' => '4', 'title' => 'Child Cat 2', 'id_parent' => '1' );
$myjunk[5] = array('id' => '5', 'title' => 'Child Cat 3', 'id_parent' => '2' );
$count = 1;
foreach ($myjunk as $oneline) {
if ($oneline['id_parent'] == 0) {
echo '<br>',$oneline['title'];
foreach ($myjunk as $secline) {
if ($secline['id_parent'] == $oneline['id']) echo '<br> ',$secline['title'];
}
}
}
?>