2014-02-15 36 views
0

下面的代碼用於從下面的XML文件中檢索「store」元素的值,並將這些值插入到數組(storeArray)中。我不希望將重複值放入數組(IE我不希望百思買插入兩次),所以我使用in_array方法來防止重複。PHP - in_array函數在檢測到URL時正常工作

此代碼工作正常:

$ xmlDoc中=使用simplexml_load_file( 「products.xml」); $ storeArray = array();

foreach($xmlDoc->product as $Product) { 
echo "Name: " . $Product->name . ", "; 
echo "Price: " . $Product->price . ", "; 

if(!in_array((string)$Product->store, $storeArray)) { 
    $storeArray[] = (string)$Product->store; 
}} 

foreach ($storeArray as $store) { 
echo $store . "<br>"; 
} 

但是,當我試圖把這些數組值(從XML存儲元素)到鏈接(如下圖所示),該值被複制(IE百思買正在顯示兩次。有什麼建議?

if(!in_array((string)$Product->store, $storeArray)) { 
$storeArray[] = "<a href='myLink.htm'>" . (string)$Product->store . "</a>"; 

foreach ($storeArray as $store) { 
echo $store . "<br>"; 
} 

下面是XML文件:

<product type="Electronics"> 
<name> Desktop</name> 
<price>499.99</price> 
<store>Best Buy</store> 
</product> 

<product type="Electronics"> 
<name>Lap top</name> 
<price>599.99</price> 
<store>Best Buy</store> 
</product> 

<product type="Hardware"> 
<name>Hand Saw</name> 
<price>99.99</price> 
<store>Lowes</store> 
</product> 

</products> 

回答

1

有一個問題,你in_array檢查要檢查,如果賣場在數組中,但實際上該鏈接添加到AR因此in_array將始終是錯誤的。

空頭支票:

// you are checking the existance of $Product->store 
if (!in_array((string)$Product->store, $storeArray)) { 
    // but add something else 
    $storeArray[] = "<a href='myLink.htm'>" . (string)$Product->store . "</a>"; 
} 

而是嘗試使用存儲爲數組鍵:

$store = (string)$Product->store; 

if (!array_key_exists($store, $storeArray)) { 
    $storeArray[$store] = "<a href='myLink.htm'>" . $store . "</a>"; 
} 
+0

謝謝,它的工作原理!應該已經意識到in_array將永遠是錯誤的鏈接! –

0

你的做法是好的。它不會將值添加到$ storeArray兩次。 我想你在你顯示的第二個代碼塊中有一個右括號的bug。 看到這個phpfiddle - 它的工作原理:

http://phpfiddle.org/main/code/1ph-6rs

您還可以使用array_unique()函數來打印唯一值。