1

好的,所以我现在正在开一家商店,以存储购物车,我使用了 $basketItems、$basketWeights 和 $basketQuantities 数组。每个索引将与篮子中的一个项目相关。

我的代码通过循环篮子中的每个项目(根据我拥有的数组)然后从数据库中提取相关信息来工作。

该代码适用于它从数据库中提取的第一行,但是一旦到达第二个项目就会失败,但我不知道为什么。

问题似乎出现在无法从 $weights 或 $prices 数组的正确索引处获取所需的值。您会在代码中注意到,为了检查数组 $weights 是否正确形成,我已经回显了它,还回显了我想要检索的索引,看起来不错,唯一的问题是它没有t echo任何东西(据我所知!)

代码如下

    <?
/*
$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 g

4

1 回答 1

0

Just a couple of notes:

  • please move sizeof() out of for-loop. do the sizeof() calc before.
  • please remove () from echo. not needed.
  • you might do calculations before outputting
  • you might use unset() at the end of the for loop, on vars newly created inside the for-loop. that would prevent overwriting stuff or reusing data from iteration before.
  • i would remove the needs to use explode() when fetching them and implode() when updating/storing them. just store/fetch the data directly in the database.
  • you know all basketItem product ids (prids), just ask the database for the whole array of basketitems (prids=1,2,3,4,123) at once. mysql syntax: WHERE prids IN('1','2','3')"; call the whole result set via mysql_fetch_assoc(). then foreach() the array. this reduces calls to the db.
  • to answer the question: i hope i'm not totally off track, but i would say that the error is $weightIndex = $basketWeights[$index]; could you please provide the $basketWeights array data. the relationship does not fit: basketWeights must be assoc, i guess, like basketWeights[prdid][weights_index].
于 2012-07-09T10:38:06.153 回答