2012-08-14 95 views
0

的結果我有以下PHP腳本:存儲foreach循環

<?php 
    session_start(); 
    global $db; 
    $cart = $_SESSION['cart']; 
    if ($cart) { 
    $items = explode(',',$cart); 
    $contents = array(); 
    foreach ($items as $item) { 
     $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; 
    } 

    $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; 
    $total=0; 
    echo 'you have following books'; 
    echo '</br>'; 
    $output[] = '<table>'; 

    foreach ($contents as $id=>$qty) { 
     $sql = "SELECT * FROM books WHERE bcode ='$id'"; 
     $result = $db->query($sql); 
     $row = $result->fetch(); 
     extract($row); 
     $output[] = '<tr>'; 

     $a = $output[] = '<td> '.$bname.'</td>'; 
     $output[] = '<td>'.$price.'rs.</td>'; 
     $output[] = '<td>*'.$qty.'</td>'; 
     '</br>'; 
     $output[] = '<td>Rs.'.($price * $qty).'</td>'; 
     $total += $price * $qty; 
     $output[] = '</tr>'; 
    } 

    $output[] = '</table>'; 
    $output[] = '<p>Grand total: <strong>Rs.'.$total.'</strong></p>'; 

    $output[] = '</form>'; 
    } else { 
    $output[] = '<p>You shopping cart is empty.</p>'; 
    } 


?> 

有沒有存儲在變量的foreach循環的結果呢? .e.e $ a將包含書名,但是如果有兩本書,$ a的價值會被下一本書覆蓋?

+0

您可以定義一個變量,例如$ bookName並將它的值設置爲sql查詢的結果,然後每次循環運行時它都會覆蓋$ bookName並使用新名稱 – 2012-08-14 18:36:52

回答

2
$a= $output[] = '<td> '.$bname.'</td>'; 

在循環的每次迭代中,您都重新初始化了$a

所有你需要做的是設置正確的函數結束時,有,比方說,在$output

$a = implode ('\n', $output); 

的破滅或者,如果你不希望整個輸出,只是用它作爲數組:

$a[] = $output[] = '<td> '.$bname.'</td>'; 
+0

我仍然獲得整個輸出。如何將它用作數組,以便我只獲取書名。 – zack 2012-08-14 18:47:47

+0

@zack - '$ a [] = $ bname'? – andrewsi 2012-08-14 18:49:01

+0

thanx男人,做了伎倆.... :-) .. – zack 2012-08-14 19:05:22

1

在的你問的是如何設置一個鍵 - 值對核心:

$books = array(); 
foreach ($items as $item) { 
    //get $bookName and $bookInformation 

    //Save 
    $books[$bookName] = $bookInformation; 
} 

因爲您指定了密鑰$bookName,所以其他名稱相同的其他名稱將使用新值($bookInformation)覆蓋密鑰($bookName)。在PHP中,如果使用結構:

$books[] = $bookInformation; 

你可以簡單的附加$bookInformation$books數組的末尾。

請注意,您的代碼還有其他一些問題。例如,從未定義$bname,並且您將輸出(echo)與業務邏輯混合(例如將書名保存到數組中)。你應該真的分開這些部分。另請注意,您至少有一行不會執行任何操作:

'</br>'; 
+1

thanx非常瞭解[]的概念,因爲im初學者的概念對我來說有點浪潮 – zack 2012-08-14 18:56:15

+0

尋找這樣一個:'$ books [$ bookName] = $ bookInformation;' - 非常感謝 – 2014-09-08 04:23:12