【问题标题】:in_array is not working even though i see a match即使我看到匹配项,in_array 也无法正常工作
【发布时间】:2013-11-20 21:05:29
【问题描述】:

我正在尝试检查 foreach 循环中是否存在重复值。

这是我的尝试,但不起作用:

$popup_array = array();
foreach($xml->config->popup as $popup_item)
    {
    $duplicate_test = $popup_item->attributes()->name; 
    if (in_array_r($duplicate_test, $popup_array)){
        echo "match found for " . $duplicate_test;
    }

    echo "item: " . $duplicate_test . "<br />";

    $popup_array[$i] = $duplicate_test;
$i++;   
    }

现在我可以清楚地看到有 2 个重复项,这是我在 print_r 结束时看到的内容,因为您可以看到 2 x 默认和 2 x 丢失,并且回显也显示默认和丢失,因此 in_array 不工作并且我不知道为什么:

[0] => SimpleXMLElement Object
    (
        [0] => Default
    )

[1] => SimpleXMLElement Object
    (
        [0] => Default
    )

[2] => SimpleXMLElement Object
    (
        [0] => pipe
    )

[3] => SimpleXMLElement Object
    (
        [0] => raised
    )

[4] => SimpleXMLElement Object
    (
        [0] => steal
    )

[5] => SimpleXMLElement Object
    (
        [0] => lost
    )

[6] => SimpleXMLElement Object
    (
        [0] => lost
    )

[7] => SimpleXMLElement Object
    (
        [0] => teach
    )

[8] => SimpleXMLElement Object
    (
        [0] => terrain
    )

我的代码有错误吗?是否与simpleXMLEelement有关,并且将其变成了多维数组,我需要以不同的方式进行搜索。如果我遍历数组并执行此操作:

$popup_length = count($popup_array);
for($x=0;$x<$popup_length;$x++)
{
echo $popup_array[$x];
echo "<br>";
}

返回:

Default
Default
pipe
raised
steal
lost
lost
teach
terrain

【问题讨论】:

  • in_array_r里面是什么? (如果未定义,则会发出致命错误)

标签: php arrays


【解决方案1】:

我觉得应该是这样的

$popup_array = array();
foreach($xml->config->popup as $popup_item)
{
    $duplicate_test = (string) $popup_item->attributes()->name; 
    if (!in_array($duplicate_test, $popup_array)){
        $popup_array[] = $duplicate_test;
    }
    else {
        echo "match found for " . $duplicate_test;
    }
}

您应该检查if not in array,然后在$popup_array 中检查push/add,无需使用$i 作为数组的索引。还要检查SimpleXMLElement::attributes

【讨论】:

    【解决方案2】:

    这个值返回一个对象,而不是一个字符串:

    $popup_item->attributes()->name
    

    因此,对象可能因名称以外的某些 XML 属性而有所不同。尝试转换为字符串,这样您的数组索引就是名称:

    $duplicate_test = (string) $popup_item->attributes()->name;
    

    【讨论】:

      【解决方案3】:

      使用array_diff

      $arr = array(1=>'word',2=>'otherword',3 =>'Hello' ,4=>'hello', 5=>'KKKKK');
      
      //Case Sensitive
      $withoutDuplicates = array_unique(array_map("strtoupper", $arr));
      $duplicates = array_diff($arr, $withoutDuplicates);
      print_r($duplicates);
      

      将打印:

      Array
      (
      [3] => Hello
      [4] => hello
      )
      

      【讨论】:

        猜你喜欢
        • 2020-07-19
        • 2018-06-23
        • 2019-03-15
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 2021-10-27
        相关资源
        最近更新 更多