我有一个可能有重复值的数组
$array1 = [value19, value16, value17, value16, value16]
我正在寻找一个有效的小PHP函数,可以接受数组或字符串(无论哪个更容易)
$array2 = ["value1", "value16", "value17"];
or
$string2 = "value1 value16 value17";
并从array1中删除array2或string2中的每个项目。
此示例的正确输出为:
$array1 = [value19]
对于那些对PHP更有经验的人来说,PHP中有这样的东西吗?
答案 0 :(得分:11)
您正在寻找array_diff
$array1 = array('19','16','17','16','16');
$array2 = array('1','16','17');
print_r(array_diff($array1,$array2));
数组([0] => 19)
答案 1 :(得分:0)
要使字符串版本正常工作,请使用explode。 像这样:
function arraySubtract($one, $two) {
// If string => convert to array
$two = (is_string($two))? explode(' ',$two) : $two;
$res = array();
foreach (array_diff($one, $two) as $key => $val) {
array_push($res, $val);
}
return $res;
}
这个allso返回一个数组,其中key = 0 .... n没有间隙
用此测试:
echo '<pre>';
print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7)));
print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7"));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6")));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6"));
echo '</pre>';