【问题标题】:Check for existing values with if in foreach?在 foreach 中使用 if 检查现有值?
【发布时间】:2015-02-09 14:20:25
【问题描述】:

我有一个已经存在值的数组:

$existingValues = array();

现在我在 xml 文件中获得了新值(是一个导入脚本),但我必须避免插入已经存在的值,我的问题是,如果我在 foreach 中列出所有来自 xml 的新值,我该怎么做?

$i = 1;

foreach($node->children() as $child) :
    $attribute2 = $child->attributes();
    $productcode = $attribute2['sku'];
    $productvariant = $attribute2['variantid'];
    $productprice = $attribute2['price'];

    if ($attribute2['sku']) :
        echo $productcode . ' - ' . $productvariant . '<br>';
    endif;

    $i++;      
endforeach;

我尝试使用in_array(),但它不正确。

【问题讨论】:

  • 你如何识别元素?我可以看到每个元素都有一些字段(skuvariantidprice)。每个元素的id是多少? sku 也许?
  • 啊抱歉,是的,我必须检查 sku,如果数组中的 sku 和 xml 中的 sku 相同,则忽略...

标签: php if-statement foreach


【解决方案1】:

您可以创建一个数组来存储产品并测试当前产品是否已经在数组中:

$i = 1;
$products = array();

foreach($node->children() as $child) :
    $attribute2 = $child->attributes();
    $productcode = $attribute2['sku'];
    $productvariant = $attribute2['variantid'];
    $productprice = $attribute2['price'];

    if ($attribute2['sku'] && !in_array($productcode, $products)) :
        echo $productcode . ' - ' . $productvariant . '<br>';
    endif;

    $products[] = $productcode;

    $i++;      
endforeach;

【讨论】:

    【解决方案2】:

    您可以创建一个$existingSKU 数组,从现有元素中提取sku。然后您可以将当前的sku 与现有的进行比较,如果不存在,您可以将元素添加到现有的。

    // build existing sku array
    $existingSKU = array();
    foreach($existingValues as $value)
    {
        array_push($existingSKU, $value['sku']);
    }
    
    // add element to existing, if not present
    foreach($node->children() as $child)
    {
        $attribute2 = $child->attributes();
    
        if(!in_array($attribute2['sku'], $existingSKU))
        {
           array_push($existingValues, $attribute2);
        }
    }
    

    由于你不使用它,你可以删除$i

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 2015-03-19
      • 2017-04-21
      • 2018-10-10
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2014-06-18
      • 2012-10-22
      相关资源
      最近更新 更多