Log in

View Full Version : Create an array from another array



toe_head2001
04-05-2009, 07:24 PM
If have and array called food (generated by form checkboxes) in which each items in that array is in its own mysql database row with another entry called price. I would like to create a second array for the prices.

I have written this code to display each price of all the item in my food array.
Having them list is fine, but I would like them to be in an array so I can easily add them up. How can I change it so it will put all the prices into an array.



foreach($food as $foodarray) {

$result = mysql_query("SELECT * FROM menu WHERE name='".$foodarray."'");

while($row = mysql_fetch_array($result))
{
echo $row['price'], " ";
}
}


Thanks.

JasonDFR
04-05-2009, 07:35 PM
If have and array called food (generated by form checkboxes) in which each items in that array is in its own mysql database row with another entry called price. I would like to create a second array for the prices.

I have written this code to display each price of all the item in my food array.
Having them list is fine, but I would like them to be in an array so I can easily add them up. How can I change it so it will put all the prices into an array.



foreach($food as $foodarray) {

$result = mysql_query("SELECT * FROM menu WHERE name='".$foodarray."'");

$price = array();

while($row = mysql_fetch_array($result))
{
$price[] = $row['price'], " ";
}
}


Thanks.

See changes above.

toe_head2001
04-05-2009, 08:40 PM
Thanks man. I had to tweak it a little, but it does what I want it to do.



$price = array();

foreach($food as $foodarray) {

$result = mysql_query("SELECT * FROM menu WHERE name='".$foodarray."'");

while($row = mysql_fetch_array($result))
{
$price[] = $row['price'];
}
}

echo array_sum($price);

JasonDFR
04-06-2009, 05:27 AM
Cool. Yeah I edited the code you posted pretty quickly and it wasn't right, but what you ended up with is right on.