php拖爆比较
php tow explode and compare
我想做的是从两个字符串中提取重复项。
我给你举个例子。
$var_1 = blue, yellow, red, purple, black
$var_2 = blue red, green, black
我最初做的是爆炸
$var1 = explode(",", $var_1);
$var2 = explode(",", $var_2);
我计算元素做一个for
$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()
2 个数组,然后 运行 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
)
我想做的是从两个字符串中提取重复项。
我给你举个例子。
$var_1 = blue, yellow, red, purple, black
$var_2 = blue red, green, black
我最初做的是爆炸
$var1 = explode(",", $var_1);
$var2 = explode(",", $var_2);
我计算元素做一个for
$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()
2 个数组,然后 运行 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
)