2014-02-15 35 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()函数来打印唯一值。