in_array不起作用,即使我看到了匹配


in_array is not working even though i see a match

我正在尝试检查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个重复,这是我在打印_r时看到的,因为你可以看到2个默认值和2个丢失值,回声也显示默认值和丢失值,所以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

我认为,它应该像这个

$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;
    }
}

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

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

$popup_item->attributes()->name

因此,这些对象可能不同于名称之外的某些XML属性。尝试转换为字符串,使数组索引仅为名称:

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

使用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
)