Results 1 to 4 of 4

Thread: Create an array from another array

  1. #1
    Join Date
    Dec 2005
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Create an array from another array

    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.

    Code:
    foreach($food as $foodarray) {
    
    	$result = mysql_query("SELECT * FROM menu WHERE name='".$foodarray."'");
    
    	while($row = mysql_fetch_array($result))
    	  {
    	  echo $row['price'], " ";
    	  }
    }
    Thanks.

  2. #2
    Join Date
    Apr 2008
    Location
    Limoges, France
    Posts
    395
    Thanks
    13
    Thanked 61 Times in 61 Posts

    Default

    Quote Originally Posted by toe_head2001 View Post
    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.

    PHP Code:
    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.

  3. The Following User Says Thank You to JasonDFR For This Useful Post:

    toe_head2001 (04-05-2009)

  4. #3
    Join Date
    Dec 2005
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    Thanks man. I had to tweak it a little, but it does what I want it to do.

    PHP Code:
    $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); 

  5. #4
    Join Date
    Apr 2008
    Location
    Limoges, France
    Posts
    395
    Thanks
    13
    Thanked 61 Times in 61 Posts

    Default

    Cool. Yeah I edited the code you posted pretty quickly and it wasn't right, but what you ended up with is right on.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •