我有一个XML文件,其中包含标记<image_file_name>
,此标记重复,偶尔还会重复此值,我正在尝试查找<image_file_name>
的唯一实例值的总数。
$simpleXML = simplexml_load_file("stock_availability.xml");
$uniqueProducts = array();
foreach ($simpleXML->product as $product) {
$image_file_name = $product->image_file_name;
if(in_array($image_file_name, $uniqueProducts)) {
echo 1;
} else {
$uniqueProducts[] = $image_file_name;
echo 2;
}
$image_file_name = null;
}
echo count($uniqueProducts);
count()
返回image_file_name
非唯一实例的实例总数。
CCD_ 5也被连续地回声,而CCD_。
我已经看了您的代码几分钟了,没有发现任何问题。我认为您使用了print_r($uniqueProducts),并在输出中发现了重复项。
您是否检查过其他重复条目中的空格或大小写差异?尝试使用一些标准化方法,例如使用strtoupper(trim())和引号。
例如:
$simpleXML = simplexml_load_file("stock_availability.xml");
$uniqueProducts = array();
foreach ($simpleXML->product as $product) {
$image_file_name = $product->image_file_name;
$dup_check=strtoupper(trim($image_file_name));
if(in_array("$dup_check", $uniqueProducts)) {
echo 1;
} else {
$uniqueProducts[] = "$dup_check";
echo 2;
}
$image_file_name = null;
}
print_r($uniqueProducts);
echo "<br>".count($uniqueProducts);
看看这是否有帮助。