我想做的是从两个字符串中提取重复。
我给你看这个例子。
$var_1 = blue, yellow, red, purple, black
$var_2 = blue red, green, black
我首先做的是爆炸
$var1 = explode(",", $var_1);
$var2 = explode(",", $var_2);
为
计算元素个数$nr1 = count($var2);
$nr2 = count($var2);
for($x = 0; $x < $nr1; $x++){
for($y = 0; $y < $nr2; $y++){
if (strcmp($var1[$x], $var2[$y]) !== 0) {
echo ($var1[$x] == $var2[$y]) ? 'true<br>' : $var1[$x].'<br>';
}
}
}
我得到了重复的结果我在var2
中缺失了blue blue blue yellow yellow yellow red red red purple purple purple
black black
,当我期望的结果是
blue, yellow, red, purple, red, green, black
有人能帮我吗?
您可以将两个数组array_merge()
,然后运行array_unique()
以删除重复项,如下所示
$var_1 = 'blue, yellow, red, purple, black';
$var_2 = 'blue, red, green, black';
$No_Dups = array_unique( array_merge( explode(",", $var_1), explode(",", $var_2)));
print_r($merged);
结果
Array
(
[0] => blue
[1] => yellow
[2] => red
[3] => purple
[4] => black
[7] => green
)