2012-06-07 48 views
1

我有一個for循環,我希望能夠將結果回顯到一個字符串中。如何才能做到這一點?它只響應循環的最後一次運行,將其用於循環外部使用的變量。echo for loop into字符串

for ($i = 0; $i < $numItem; $i++) { 
      extract($cartContent[$i]); 

     $pricebands = array("1"=>"$pd_price1","2"=>"$pd_price2","3"=>"$pd_price3","4"=>"$pd_price4","5"=>"$pd_price5","6"=>"$pd_price6"); 
     if(isset($loggedInfo['price'])){ 
      $priceToShow = $pricebands[$loggedInfo['price']]; 
     } else { 
      $priceToShow = $pricebands[1]; 
     } 
      $productUrl = "index.php?c=$cat_id&p=$pd_id"; 
      $subTotal += $priceToShow * $ct_qty; 
      $pd_name; 
      $ct_qty; 
      $productList = "L_NAME".$i."=".$pd_name."&L_AMT".$i."=".$priceToShow."&L_QTY".$i."=".$ct_qty."&"; 
     } 
     $amount = $subTotal;   
    } 

和變量把$ productList的成

$nvpstr="&PAYMENTACTION=$paymentType&AMT=$amount&".trim($productList)."CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$countryCode&CURRENCYCODE=$currencyCode"; 

回答

5

你每次循環重置$ productList的。要添加到它,而不是將其設置:

$productList .= 'new stuff...'; 

循環之前,該變量設置爲空字符串,您將添加更多的字符:

$productList = ''; 
+0

謝謝,我把變量之外的空變量放在循環之前,你發佈哈哈,再次感謝! – ngplayground

0

字符串Concatination或崩潰。

我有點困惑於你想加入的確切字符串,沒有回聲。

for ($i = 0; $i < $numItem; $i++) { 
     extract($cartContent[$i]); 

    $pricebands = array("1"=>"$pd_price1","2"=>"$pd_price2","3"=>"$pd_price3","4"=>"$pd_price4","5"=>"$pd_price5","6"=>"$pd_price6"); 
    if(isset($loggedInfo['price'])){ 
     $priceToShow = $pricebands[$loggedInfo['price']]; 
    } else { 
     $priceToShow = $pricebands[1]; 
    } 
     $productUrl = "index.php?c=$cat_id&p=$pd_id"; 
     $subTotal += $priceToShow * $ct_qty; 
     $pd_name; 
     $ct_qty; 
     $productList .= "L_NAME".$i."=".$pd_name."&L_AMT".$i."=".$priceToShow."&L_QTY".$i."=".$ct_qty."&"; 
    } 
    $amount = $subTotal;   
}