2013-11-20 38 views
0

我試圖檢查在foreach循環中是否有重複的值。即使我看到一場比賽in_array不工作

這是我嘗試它不工作:

$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個默認和2×丟失回波還顯示默認的,失去了所以in_array不工作和IM不知道爲什麼:

[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 
+2

什麼! 'in_array_r'? –

+0

什麼是'in_array_r'? –

+0

什麼是_inide_'in_array_r'? (如果沒有定義,它會發出致命的錯誤) – NorthBridge

回答

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

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 
) 
0

該值將返回對象,而不是字符串:

$popup_item->attributes()->name 

因此,對象可能是由一些不同的XML比name屬性等。嘗試強制轉換爲字符串,這樣你的數組索引僅僅是名稱:

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