此数组中的值是通过拉取XML值(使用simplexml_load_file方法)和foreach循环插入的。
$skuArray(2, 4, 3, 7, 7, 4, 1, 7, 9);填充数组后,我需要检查数组中是否存在任何重复的值(在本例中为7和4)。Product->sku在下面的foreach循环中包含XML值(来自skuArray文件)。下面的代码不起作用。有什么建议吗?谢谢!
foreach($XMLproducts->product as $Product) {
if (in_array($Product->sku, $skuArray, > 1) {
// execute code
}
}发布于 2014-03-18 07:59:29
使用array_count_values()获取某个值出现的次数,然后检查该值是否不止一个
$skuArray = array(2, 4, 3, 7, 7, 4, 1, 7, 9);
$dupes = array_count_values($skuArray);
foreach($XMLproducts->product as $Product) {
if ($dupes[$Product->sku] > 1) {
// execute code
}
}发布于 2014-03-18 08:07:33
如果您需要删除重复项,则可以使用array_unique
<?php
$input = array(4, 4, 3, 4, 3, 3);
$result = array_unique($input);
// $result = array(4, 3)
?>如果您只需要检查是否存在重复项,则可以使用array_count_values进行检查
<?php
$input = array(2, 4, 3, 7, 7, 4, 1, 7, 9);
$counts = array_count_values($input);
$duplicates = array();
foreach($counts as $v => $count){
if($count > 1)
$duplicates[] = $v;
}然后,您将拥有一个包含重复值的数组$duplicates。
发布于 2014-03-18 08:09:43
您的代码有拼写错误:
if (in_array($Product->sku, $skuArray, > 1) {in_array期望第一个参数是针,但您提到的"Product->sku包含skuArray值",无论如何,它应该是这样的:
if (in_array($Product->sku, $skuArray)) {https://stackoverflow.com/questions/22467816
复制相似问题