即使我看到匹配,in_array也无法正常工作

时间:2013-11-20 21:05:29

标签: php arrays

我正在尝试检查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

3 个答案:

答案 0 :(得分: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内检查push/add然后$popup_array,不需要使用$i作为数组的索引。另请查看SimpleXMLElement::attributes

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

$popup_item->attributes()->name

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

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