简体   繁体   中英

Foreach inside foreach PHP

I'm trying to make a PHP/Oracle SQL website and I'm having trouble putting a foreach iteration inside another one.

foreach($orders as $order) {
    if($order["email"] == $email){
echo "<p>".
"<strong>".
"Order: ".$order["ordernumber"].
"</strong>".".".
"</p>";
    }
        foreach($lines as $line){
            if($order["ordernumber"] == $line["ordernumber"] && 
               $line["email"] == $email){
                 echo "<p>".
                 "<strong>".
                 $line["name"].": ".$line["ammountordered"]." units"."
                 </strong>".". ".
                 "</p>"; 
            }
        }

}

$orders is a query that contains all orders made, for each order first I check if the order is made by a client whose email is the same as the one he is logged in with ($email variable). It just prints the order number.

$lines is a second query that contains all order lines in the database, associated with an order number as a foreign key.

With the next foreach I pretend that once an order number is printed it shows all the order lines belonging to that order, the if does the filter and it works JUST on the first iteration of $orders.

Order: 330000.

Small box 60mm: 500 units.

Medium-sized box 40mm : 1000 units.

Big box 1cm : 300 units.

Order: 330002.

This is what is shown on the website, but order 330002 has order lines in the database so they should be printed, but there should be something wrong with what I'm doing since it seems like it works just with the first index of the $orders iteration.

Going on a limb here, because shots in the dark work well.

If you var_dump($lines) , you'll probably see a generator, or some DB object. Not an array.

You can't foreach twice over the same generator/DB object.

Instead, consider using $lines = iterator_to_array($lines); or some other method of "converting" the result set into an array before using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM