nickycla Posted October 7, 2008 Share Posted October 7, 2008 Hello. Please could someone out there help a newbie? I have a simple array (just numbers read from mysql). I want to run a mysql query on each element in the array, and depending on the result of that, add more elements to the array. I have tried a foreach loop, but i guess it must calculate the number of elements at the start of the loop, as it does not execute for any that are added within the loop (a foreach..echo after the loop confirms they have been added ok). My question is, is there someway to make it re-calculate the number of elements from within the loop, or should i try some other method? Thanks Link to comment https://forums.phpfreaks.com/topic/127391-adding-elements-to-an-array-within-a-foreach-loop/ Share on other sites More sharing options...
Bendude14 Posted October 7, 2008 Share Posted October 7, 2008 lets see what you have already tried and we might be able to help you advance on that... how about another loop after the keys added inside the loop Link to comment https://forums.phpfreaks.com/topic/127391-adding-elements-to-an-array-within-a-foreach-loop/#findComment-658988 Share on other sites More sharing options...
nickycla Posted October 7, 2008 Author Share Posted October 7, 2008 This is what i have: foreach ($menu_array as $currid) { $query = "select nodes.id, nodes.type from nodes where nodes.parent = $currid"; $result=mysql_query($query)or die(mysql_error()); $num=mysql_num_rows($result); if ($num > 0){ $i=0; while ($i < $num) { $thisid=mysql_result($result,$i,"nodes.id"); $nodetype=mysql_result($result,$i,"nodes.type"); if ($nodetype == "M") { $menu_array[$mai] = $thisid; $mai++; echo "Adding Menu ", $thisid, " as number ", $mai, "<br>"; } else { $product_array[$pai] = $thisid; $pai++; echo "Adding Product ", $thisid, " as number ", $pai, "<br>"; } $i++; } } echo "Curr id ", $currid . "<br />"; } foreach ($menu_array as $value) { echo "MENU ARRAY", $value . "<br />"; } Each 'nodes' record is either a menu or a product, and has an id, and a parent id. Starting with a menu node i am trying to drill down through all the lower level nodes, until i have all the products within these menus in my product array. Could be any number of menus below the current one. Link to comment https://forums.phpfreaks.com/topic/127391-adding-elements-to-an-array-within-a-foreach-loop/#findComment-658993 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.