2012-07-01 123 views
1

好吧因此,我正在創建一個商店,以存儲購物車,我正在使用$ basketItems,$ basketWeights和$ basketQuantities數組。每個索引將與籃子中的物品有關。PHP無法通過索引提取數組值

我的代碼通過循環遍歷籃子中的每個項目(根據我擁有的數組),然後從數據庫中提取相關信息。

該代碼很適合從數據庫中提取的第一行,但是一旦它到達第二項就會失敗,但我不知道爲什麼。

問題似乎發生在無法從$ weights或$ prices數組獲得正確索引所需的值。你會注意到在代碼中,爲了檢查數組$權重是否正確地形成,我已經echo'd它,也echo'd索引我想檢索,這看起來好,唯一的問題是,它不'牛逼呼應什麼(只要我可以告訴!)

的代碼如下

<? 
/* 
$basketItems 
$basketWeights 
$basketProducts 

are arrays, each value stores the index of the item relating to the product in the database */ 

//show basket, go through all the basket items, the retrieves relevant information from the database 
for($index = 0; $index < sizeof($basketItems); $index++) 
{ 
    //get product at this index 
    $getProduct = mysql_query("SELECT * from shop_products where prid='".$basketItems[$index]."' limit 1") or die(mysql_error()); 
    $product = mysql_fetch_array($getProduct); 
    //weights is an array for each product ie 100, 200, 500 
    $weights = explode(",", $product['prweights']); 
    $weightIndex = $basketWeights[$index]; 
    $prices = explode(",", $product['prprices']); 
?> <tr> 
<td><b><? print_r(array_values($weights)); ?></b></td> 
</tr><tr> 
    <td><? echo($product['prtitle']); ?></td> 
    <td><? echo ("$weightIndex/$weights[$weightIndex]"); ?>g</td> 
    <td><? echo($basketQuantities[$index]); ?></td> 
    <td><? echo $prices[$weightIndex]; ?></td> 
    <td><? echo ($prices[$weightIndex] * $basketQuantities[$index]); ?></td> 
    <td>&nbsp;</td> 
    </tr> 
    <? 

    } 
?> 

而且結果可以在這裏看到: http://www.jamesmoorhouse.co.uk/images/shop.png

正如你從截圖中可以看到,它只是不會迴應任何應該回顯每個產品上方的數組結果的結果。

測試的第2列的格式是arrayIndex/arrayValueAtIndex摹

+1

您正在打印'array_values($ weights)',但返回的是什麼?<?的print_r($權重); (請注意,array_values可能會分配新的索引) –

+0

這仍然會返回相同的 Array([0] => 100 [1] => 250 [2] => 500) Planters Breakfast \t 0/100g 2。00 陣列([0] => 100) 花盆下午\t 0 /克 我認爲有可能在第一已發生,所以我試圖每次循環的時間來清空陣列for語句,但那不起作用 –

+0

奇怪,第一個條目後返回mysql_num_rows()是什麼? –

回答

0

只是一對夫婦的注意事項:

  • 請移動的sizeof()出於對循環。先做sizeof()計算。
  • 請從回聲中刪除()。不需要。
  • 你可能會輸出
  • 你可以使用未設置()在for循環結束前做計算,在瓦爾for循環中新創建的。這會阻止覆蓋內容或重複使用之前的數據。
  • 我會刪除需要使用爆炸()時提取他們和implode()時更新/存儲他們。只是直接在數據庫中存儲/獲取數據。
  • 您知道所有basketItem產品id(prid),只需向數據庫提供整個basketitems數組(prid = 1,2,3,4,123)。 mysql語法:WHERE prids IN('1','2','3')";通過mysql_fetch_assoc()調用整個結果集。然後foreach()數組。這減少了對數據庫的調用。
  • 回答這個問題:我希望我不是完全偏離軌道,但我會說錯誤是$weightIndex = $basketWeights[$index];可以請您提供$ basketWeights數組數據。關係不適合:basketWeights必須是assoc,我猜,像basketWeights [prdid] [weights_index]。