我有这段代码可以返回3个数组,我想检查所有3个数组中是否有重复项,然后仅保留1个值。但是因为数组是在循环中生成的,所以array_unique / array_ diff不能工作。
这个问题有解决方案吗?
foreach ($ci AS $i) {
if($i == 0){
continue;
}
$cfsi = $cate->getCategoriesFeatureID($i);
echo "<pre>";
print_r($cfsi);
echo "</pre>";
}
我得到的结果
Array
(
[0] => 14
[1] => 15
[2] => 16
[3] => 18
[4] => 19
[5] => 20
[6] => 27
)
Array
(
[0] => 14
[1] => 15
[2] => 16
[3] => 17
[4] => 18
[5] => 19
[6] => 20
[7] => 21
[8] => 27
[9] => 28
)
Array
(
[0] => 11
[1] => 14
[2] => 16
[3] => 18
[4] => 19
[5] => 27
[6] => 28
)
我正在寻找的结果
Array
(
[0] => 14
[1] => 15
[2] => 16
[3] => 18
[4] => 19
[5] => 20
[6] => 27
)
Array
(
[0] => 17
[1] => 21
[2] => 28
)
Array
(
[0] => 11
)
答案 0 :(得分:2)
您可以做的是存储先前显示的内容,并且每次仅报告从当前值到此先前值的差异(使用array_diff()
)。然后在循环结束时,将当前值移到先前的值。
$previous = [];
foreach ($ci AS $i) {
if($i == 0){
continue;
}
$cfsi = $cate->getCategoriesFeatureID($i);
$difference = array_values(array_diff($cfsi, $previous));
echo "<pre>";
print_r($difference);
echo "</pre>";
$previous = $cfsi;
}