【问题标题】:PHP - in_array function working correctly when detecting URL'sPHP - in_array 函数在检测 URL 时正常工作
【发布时间】: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>

【问题讨论】:

    标签: php xml arrays


    【解决方案1】:

    您的in_array 支票存在问题。您正在检查存储是否在数组中,但实际上将链接添加到数组,因此in_array 将始终为 false。

    空头支票:

    // 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 作为数组键:

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

    【讨论】:

    • 谢谢,它有效!应该已经意识到 in_array 的链接总是错误的!
    【解决方案2】:

    你的方法很好。它不会将值添加到 $storeArray 两次。 我认为您在显示的第二个代码块中有一个带有右括号的错误。 看到这个 phpfiddle - 它的工作原理:

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

    您还可以使用 array_unique() 函数来打印唯一值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多