Forum Moderators: coopster

Message Too Old, No Replies

php looping array sproblem

my brain hurts

         

HelenDev

1:34 pm on Apr 19, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all,

I am having problems. I have a list of categories in an array. I want to loop through the array and make a table of results for each category. No problems with this. However, I also want to check to see if there are any sub categories listed in each category, and get a list of these. I have got myself in a terrible loopy mess over this, although I am sure it should be quite simple! I can make an array of the subcategories, but it gets added to every time I loop through each main category. In short, I need it to make one array of subcategories for each category.

Here is my code, I'll try and keep this as short as I can...

//I have an array of categories - I want each category in it's own table on the page...

foreach($categories as $cat) {

print('<p>Title: '.$cat.'<p>');

//find out if this category has any subcategories - this is the part that doesn't work properly

$subcat_query = mysql_query("SELECT * FROM bargains WHERE category = '$cat'",$db);
if ($subcatrow = mysql_fetch_assoc($subcat_query)) {
do{
$subcats[] = $subcatrow[subcategory];
} while ($subcatrow = mysql_fetch_assoc($subcat_query));
// remove duplicates
$subcats = array_unique($subcats);
print_r($subcats);
}

// print the main category table - this part works fine

$this_query = mysql_query("SELECT * FROM bargains WHERE category = '$cat'",$db);

if ($myrow = mysql_fetch_array($this_query)) {
print('<table>');
do {
printf('<tr><td>'.$myrow[description].'</td><td>'.$myrow[price].'</td></tr>');
} while ($myrow = mysql_fetch_array($this_query));
print('</table>');
}

}

Any help would be appreciated. Maybe I need some coffee...

HelenDev

4:11 pm on Apr 19, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have now solved my problem. Solution involved imploding my array, seeing if there was anything in it and if so, reassembling it and looping through. If anyone really wants to see the finished code I will of course happily oblige ;)