PHP无法通过索引提取数组值

时间:2012-07-01 19:23:45

标签: php arrays

好的所以我现在正在开店,存放购物车我正在使用$ 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

正如您从屏幕截图中看到的那样,它不会回应任何应该回显每个产品上方阵列结果的内容。

第二列的测试格式是arrayIndex / arrayValueAtIndex g

1 个答案:

答案 0 :(得分:0)

只是几个笔记:

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