foreach循环不起作用

时间:2015-08-04 07:32:50

标签: php foreach

我有一个for循环如下,在循环内如果我打印我得到一个输出但是当我在循环外打印我得到单个值。

        $sql = 'SELECT productID,is_senioramtper,senioramt,p.id_product as productid,p.price as price FROM ps_product as p join ps_damc_products as pd on p.id_product = pd.productID  where is_senior_active =1';
                  if ($allproducts = Db::getInstance()->Executes($sql))
                      foreach($allproducts as $prod){
                        $amount = array();
                        if ($prod['is_senioramtper'] == 1)
                        {                                                       
                            $amount[$prod['productID']]=$prod['senioramt'];

                        }

                        elseif ($prod['is_senioramtper'] == 2){

                            $peramt = $prod['senioramt'];
                            $cal = ($peramt*$prod['price'])/100;
                            $amount[$prod['productID']] = $cal;
                            }
                        }

                        $prodwiseamt =json_encode($amount);
                        echo"<pre>";
                    var_dump ($prodwiseamt);

我希望在循环之外的$ prodwiseamt​​中得到结果。这是什么问题?

2 个答案:

答案 0 :(得分:0)

 $sql = 'SELECT productID,is_senioramtper,senioramt,p.id_product as productid,p.price as price FROM ps_product as p join ps_damc_products as pd on p.id_product = pd.productID  where is_senior_active =1';
                          if ($allproducts = Db::getInstance()->Executes($sql))
                              $amount = array();
                              foreach($allproducts as $prod){

                                if ($prod['is_senioramtper'] == 1)
                                {                                                       
                                    $amount[$prod['productID']]=$prod['senioramt'];

                                }

                                elseif ($prod['is_senioramtper'] == 2){

                                    $peramt = $prod['senioramt'];
                                    $cal = ($peramt*$prod['price'])/100;
                                    $amount[$prod['productID']] = $cal;
                                    }
                                }

                                $prodwiseamt =json_encode($amount);
                                echo"<pre>";
                            var_dump ($prodwiseamt);

您正在每次迭代中初始化$amount数组,因此分配的值将丢失。 试试这段代码

答案 1 :(得分:0)

  if ($prod['is_senioramtper'] == 1)
                    {                                                       
    $amount[$prod['productID']][]=$prod['senioramt'];

   }
   elseif ($prod['is_senioramtper'] == 2)
   {
         $peramt = $prod['senioramt'];
         $cal = ($peramt*$prod['price'])/100;
         $amount[$prod['productID']][] = $cal;
   }