PHP 无法按索引提取数组值


PHP cannot extract array values by index

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

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

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

无法

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

代码如下

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

只是几个注意事项:

  • 请将 sizeof() 移出 for 循环。 之前做 sizeof() 计算。
  • 请从回声中删除 ()。 不需要。
  • 您可以在输出之前进行计算
  • 您可以在 for 循环的末尾使用 unset(),在 for 循环中新创建的变量上。 这将防止覆盖内容或重用之前迭代的数据。
  • 我会删除在获取它们时使用 explode() 并在更新/存储它们时使用 implode() 的需要。 只需直接在数据库中存储/获取数据即可。
  • 您知道所有篮子项目产品ID(prids),只需一次向数据库询问整个篮子项目数组(prids=1,2,3,4,123)。 MySQL 语法: WHERE prids IN('1','2','3')";通过mysql_fetch_assoc()调用整个结果集。 然后 foreach() 数组。 这减少了对数据库的调用。
  • 回答这个问题:我希望我没有完全偏离轨道,但我想说错误是$weightIndex = $basketWeights[$index]; 您能否提供$basketWeights数组数据。 这种关系不合适:篮筐权重一定是assoc,我猜,就像篮子重量[prdid][weights_index]。