在foreach中未设置工作但不是:s

时间:2015-03-09 19:50:54

标签: php unset

有人可以解释一下吗?

foreach ($xml as $product) {

为什么这会删除节点

   unset ($product->itemspecific);
   unset ($product->properties);

但这不会删除整个元素吗?

   unset ($product);
}

修改

$result = $soap->GetFeedXML( array('accessKey' => $feed) );

//Write XML data to file
$bytes = file_put_contents($file,$result->GetFeedXMLResult);
$xml = new SimpleXMLElement($result->GetFeedXMLResult);

foreach ($xml as $product) {
//Remove fluous properties
unset ($product->ebay_itemspecific);
unset ($product->StoneProperties);
unset ($product->StoneValues);
unset ($product->UserCity);
unset ($product->eBayStartingPrice);
unset ($product->ebay_quantity);
unset ($product->ebay_variation);
unset ($product->Amazon_Metal_Type);
unset ($product->Amazon_Item_Type);
unset ($product->Ebay_Category_Number);
unset ($product->DropshipUser_Zip);
unset ($product->DropshipUser_Company);
unset ($product->PayPal_Email_Address);

 //Convert different product sizes into options for the single product
 $x = strpos($product->StockNo,"-");

 if ($x > 0) {
      $stock = substr($product->StockNo,0,$x);
      $size = substr($product->StockNo,$x+1);

      //Find the parent
      $p = $xml->xpath("ProductFeedEntity[StockNo='$stock']");
      $option = $p[0]->addChild("Options")->addChild("Size");
      $option->addChild("Name","Size");
      $option->addChild("Value", $size);
      $option->addChild("CostPrice", $product->CostPrice);

      echo "<i>&nbsp;&nbsp;Added size: " . $size . "</i><br>";

这就是问题所在。我已尝试使用$ index而没有。我尝试过未设置($ xml [$ index]),但这也不起作用。

       //Remove the sized product
      unset($product[$index]);
 } else
      echo $product->StockNo . " - " . $product->ItemTitle . "<br>";

 $index++;
}

$xml->asXml($file);

XML

<ProductFeedEntity>
    <StockNo>123</StockNo>
    <MoreNodes>XXX</MoreNodes>
    <MoreNodes>XXX</MoreNodes>
</ProductFeedEntity>

<ProductFeedEntity>
    <StockNo>456</StockNo>
    <MoreNodes>XXX</MoreNodes>
    <MoreNodes>XXX</MoreNodes>
</ProductFeedEntity>

<ProductFeedEntity>
    <StockNo>456-A</StockNo>
    <MoreNodes>XXX</MoreNodes>
    <MoreNodes>XXX</MoreNodes>
</ProductFeedEntity>

<ProductFeedEntity>
    <StockNo>789</StockNo>
    <MoreNodes>XXX</MoreNodes>
    <MoreNodes>XXX</MoreNodes>
</ProductFeedEntity>

1 个答案:

答案 0 :(得分:0)

您正在迭代一个对象(SimpleXMLElement),因此您应该使用正确的语法来取消SimpleXMLElement中的元素设置。

试试这个:

foreach($xml as $key => $product) {
    // ...
    unset($xml->$key);
}

从您的示例中可以看出,当您使用$index++时,您正在生成密钥。 foreach提供了在循环中获取数组键的功能,因此您应该尝试使用它。