【发布时间】:2014-02-15 17:50:10
【问题描述】:
下面的代码用于从下面的 XML 文件中检索“store”元素的值,并将这些值插入到数组(storeArray)中。我不希望将重复值放入数组中(即我不希望 Best Buy 插入两次),所以我使用 in_array 方法来防止重复。
这段代码运行良好:
$xmlDoc = simplexml_load_file("products.xml"); $storeArray = 数组();
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 Best Buy 显示两次。有什么建议吗?
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>
【问题讨论】: