我试图从Prestashop 1.7导出产品到一个XML。一切都很好,但脚本导出一个产品多次,这取决于所属的类别。例如Product1是在所有产品 - 衣服 - 男人,在这种情况下,将导出3次XML。
我尝试使用基于产品ID的array_unique,但它不工作。谁能,请给我指出正确的方向?
完整的代码可以在这里找到。https:/pastebin.comMQxfYSj2
在这部分代码中,我尝试使用array_unique,但没有结果。
private function getProductFromArray($arrProduct){
$objProduct = new Okazii_Connector_Product();
$objProduct->ID = $arrProduct['id_product'];
$objProduct->UniqueID = $arrProduct['id_product'];
$objProduct->Title = $arrProduct['name'];
if (mb_strlen($arrProduct['description']) > 3){
$objProduct->Description = $arrProduct['description'];
} else if (mb_strlen($arrProduct['description_short'])) {
$objProduct->Description = $arrProduct['description_short'];
} else {
$objProduct->Description = $arrProduct['name'];
}
$objProduct->Amount = $arrProduct['quantity'];
if ($objProduct->Amount == 0){
$objProduct->Amount = $this->getAmountFromStock($arrProduct['id_product']);
}
$objProduct->Category = $this->getCategoryString($arrProduct['id_category']);
$objProduct->Currency = $this->getCurrency();
$objProduct->Price = $arrProduct['price'];
if(!empty($arrProduct['available_now']) && $objProduct->Amount > 0)
{
$objProduct->InStock = $arrProduct['available_now'];
}
if(!empty($arrProduct['gtin']))
{
$objProduct->GTIN = $arrProduct['gtin'];
}
else if(!empty($arrProduct['ean13']))
{
$objProduct->GTIN = $arrProduct['ean13'];
}
else if(!empty($arrProduct['isbn']))
{
$objProduct->GTIN = $arrProduct['isbn'];
}
$this->setProductImages($objProduct);
$this->setProductBrand($objProduct, $arrProduct['id_manufacturer']);
return $objProduct;
}
我还试着在脚本的顶部根据产品ID来获取唯一的产品,但没有效果。
其他有用的信息。PHP 7.2, Prestashop 1.7.6.5。
尝试在类的最开始创建一个属性,如
private $exportedProductsIds = [];
然后在每次迭代后,在返回前把导出的产品id放入其中。
array_push($this->exportedProductsIds, $objProduct->id);
然后在运行前添加一个验证,如果id已经在 $exportedProductsIds
然后跳过
if (!in_array($objProduct->id, $this->exportedProductsIds)) {
//run your code
}
但我认为最好的地方是将这段代码放在你调用 getProductFromArray
方法从。
我假设这样
private function exportProducts($products)
{
foreach ($products as $product) {
if (in_array($objProduct->id, $this->exportedProductsIds)) {
continue;
}
if ($this->getProductFromArray($arrProduct)) {
array_push($this->exportedProductsIds, $objProduct->id);
}
}
}