PHP变量范围混乱

时间:2010-11-14 18:34:28

标签: php variables scope

您好
这是我的代码....问题出在$product变量 有什么方法可以解决这个问题吗? 它定义了两次并导致问题覆盖

问题更新

   $productsIDs = array();
        foreach ($rowsProducts as &$product) {
            $product["features"] = &$productsFeatures[$product["product_id"]];
            $productsIDs[] = $product["product_id"];
        }

//GET STOCK FEATURES
$sqlIds=implode(",",$productsIDs);
$sql="SELECT * FROM eshop_products_stock WHERE product_id IN ($sqlIds)";

$productsStock = $db->getRecordSet($sql);
$sql="SELECT * FROM `eshop_features_valuestr` WHERE feature_id IN ".
      "(SELECT DISTINCT feature1_id FROM eshop_products_stock WHERE product_id IN ($sqlIds))" .
        " AND language_code='$lang'";

$productsSizes = $db->getRecordSet($sql);
 $sql="SELECT * FROM `eshop_features_valuestr` WHERE feature_id IN ".
      "(SELECT DISTINCT feature2_id FROM eshop_products_stock WHERE product_id IN ($sqlIds))".
        " AND language_code='$lang'";;
$productsColors = $db->getRecordSet($sql);

$productsSizesV=array();
foreach($productsSizes as $size)
{
    $productsSizesV[$size["value"]]=$size["title"];
}

$productsColorsV=array();
foreach($productsColors as $color)
{
    $productsColorsV[$color["value"]]=$color["title"];
}
//Group by product stock
$productsStockV=array();
$product="";

foreach($productsStock as $product)
{
   $productsStockV[$product["product_id"]]["sizes"][]=$product["feature1_value"];
   $productsStockV[$product["product_id"]]["colors"][]=$product["feature2_value"];
}

2 个答案:

答案 0 :(得分:4)

您应该在$product循环后取消设置foreach

foreach ($rowsProducts as &$product) {
      $product["features"] = &$productsFeatures[$product["product_id"]];
      $productsIDs[] = $product["product_id"];
}
unset($product);

答案 1 :(得分:3)

你遇到了一个非常好的php WTF: foreach ($rowsProducts as &$product)使$ product成为引用。不仅是循环,而且永远。如果你以后使用$ product作为循环变量使用foreach(或者写任何写入$ product的东西),它将覆盖第一个foreach循环的最后一项。

如果您更改了任何内容,只需使用foreach ($rowsProducts as $key => $product)并在循环体的末尾指定$rowsProducts[$key] = $product;

另一种解决方案是在第一次循环后调用unset($product);来删除引用。但通常不使用引用循环更安全,因为你不能忘记取消设置。