Jump to content

Adding elements to an array within a foreach loop


nickycla

Recommended Posts

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

 

 

 

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.