简体   繁体   English

Foreach在foreach PHP中

[英]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. 我正在尝试建立一个PHP / Oracle SQL网站,但在将foreach迭代放入另一个迭代时遇到了麻烦。

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). $ orders是一个查询,其中包含所有已下达的订单,对于每个订单,我首先检查该下单是否由客户执行,该客户的电子邮件与他使用($ email变量)登录的电子邮件相同。 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. $ lines是第二个查询,它包含数据库中的所有订单行,并与作为外键的订单号相关联。

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. 在下一个foreach中,我假设一旦打印了订单号,它将显示属于该订单的所有订单行,如果进行过滤,则它仅对$ 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. 这就是网站上显示的内容,但是订单330002在数据库中有订单行,因此应该将其打印出来,但是我正在做的事情应该有问题,因为它似乎只适用于$的第一个索引订单迭代。

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. 如果您使用var_dump($lines) ,则可能会看到一个生成器或某些数据库对象。 Not an array. 不是数组。

You can't foreach twice over the same generator/DB object. 您不能在同一个生成器/数据库对象上进行两次foreach

Instead, consider using $lines = iterator_to_array($lines); 相反,请考虑使用$lines = iterator_to_array($lines); or some other method of "converting" the result set into an array before using it. 或在使用结果集之前将其“转换”为数组的其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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