计算数组中的重复值

时间:2013-09-02 06:34:19

标签: php arrays

使用以下代码计算值不会将结果转换为我的数组。非常感谢任何对我做错的帮助。

$xml=simplexml_load_file("sitemap.xml");

$arr = array();
foreach($xml->url as $child)
{
    if (isset($child->loc)) {
        echo "true";
        $arr[] = $child->loc;
    } else {
        echo "error";
        echo  $child->loc; 
    }        
}
print_r(array_count_values($arr));

3 个答案:

答案 0 :(得分:3)

您必须正确转换项目值,否则您将在阵列中存储SimpleXMLElement对象:

$arr[] = (string)$child->loc;

答案 1 :(得分:0)

杰克回答后形成的解决方案。添加此代码以检查重复项。

if(count($arr) != count(array_unique($arr))){
      echo "Duplicates";
   }

答案 2 :(得分:0)

可能会像这样期待

$xml=simplexml_load_file("sitemap.xml");

echo "<pre>";
var_dump($xml->url->loc[0]);
var_dump($xml->url->loc[1]);
var_dump($xml->url->loc[2]);

echo "</pre>";

$arr = array();

foreach($xml->url as $child)
{
    foreach($child as $tmp){    
        if (isset($tmp)) {
            echo "true";
            $arr[] = (String)$child->loc;
        } else {
            echo  "error<br/>";
            echo  $child->loc; 
        }    
    }    
}
print_r(array_count_values($arr));



<sites>
    <url>
        <loc>google.com</loc>
        <loc>google.com</loc>
        <loc>yahoo.com</loc>
    </url>
</sites>
相关问题