【问题标题】:Loop within a loop adding to a $total循环内循环添加到 $total
【发布时间】:2013-08-03 13:18:45
【问题描述】:

我被困在我认为会是一个简单的循环上。

我希望完成的是合计一个购物篮的内容,但不添加其他用户总数。这是一个非常简化的示例:

这会很完美

        foreach($BasketItems as $Items)
        {
            if(strstr($Items, "Book") !== false)
            {
                $ItemPrice += $Items["Price"];
            }
        }

但不幸的是,它的构造方式使其也循环通过所有用户,例如:

for($Loop = 0; $Loop < mysql_num_rows($Data); $Loop++)
{
        foreach($BasketItems as $Items)
        {
            if(strstr($Items, "Book") !== false)
            {
                $ItemPrice += $Items["Price"];
            }
        }
}

此示例的问题在于它将以前的用户 $ItemPrice 添加到当前用户等等。非常感谢任何帮助。

【问题讨论】:

    标签: php for-loop foreach nested-loops


    【解决方案1】:

    试试看,

    for($Loop = 0,$len=mysql_num_rows($Data); $Loop < $len; $Loop++)
    {
        foreach($BasketItems as $Items)
        {
           if(strstr($Items, "Book") !== false)
           {
              $ItemPrice[$Loop] += $Items["Price"]; 
              // use Array of $ItemPrice for every user, 
              //you can use user_id here to fetch
           }
        }
    }
    

    【讨论】:

    • 谢谢,这似乎是正确的轨道。此循环创建一个价格数组,用于计算总价。例如$ItemPrice("2.99","4.99") 而不是$ItemPrice,其值为"7.98"
    猜你喜欢
    • 1970-01-01
    • 2013-09-02
    • 2016-01-30
    • 2012-12-22
    • 2014-06-18
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多