我的目的是减少与数字匹配的元素从一个数组到另一个数组。
$my_elements = "329,330,331,332,333,334,335,336,337,338,339,340";
$my_array =array(329,330,331,332,333,334,335,336,337,338,339,340,341,342,359);
$to_remove = array($my_elements);
$result = array_diff($my_array,$to_remove);
$str_comp=implode(",", $result);
echo $str_comp;
我要显示此结果:
341,342,359
请对此提供帮助。
$my_elements = "329,330,331,332,333,334,335,336,337,338,339,340";
$my_array =array(329,330,331,332,333,334,335,336,337,338,339,340,341,342,359);
$to_remove = array($my_elements);
$result = array_diff($my_array,$to_remove);
$str_comp=implode(",", $result);
echo $str_comp;
答案 0 :(得分:2)
您的$to_remove
应该是$my_elements
字符串中的数字数组。但是,使用array($my_elements)
不会这样做。您需要explode
字符串来获取数字数组:
$my_elements = "329,330,331,332,333,334,335,336,337,338,339,340";
$my_array =array(329,330,331,332,333,334,335,336,337,338,339,340,341,342,359);
// Change is here
$to_remove = explode(',', $my_elements);
$result = array_diff($my_array,$to_remove);
$str_comp=implode(",", $result);
echo $str_comp;
答案 1 :(得分:1)
遍历数组,如果第二个数组中不存在值,则将其推入新数组中
$data = explode(",",$my_elements)
$finalData = array();
foreach($data as $value){
if(!in_array($value,$my_array)){
$finalData[] = $value;
}
}
$finalData
将满足您的需求。
答案 2 :(得分:0)
my_elements应该是一个数组
$my_elements = explode(',',"329,330,331,332,333,334,335,336,337,338,339,340");
用以下代码替换您的代码:-
$my_elements = explode(',',"329,330,331,332,333,334,335,336,337,338,339,340");
$my_array =array(329,330,331,332,333,334,335,336,337,338,339,340,341,342,359);
$result = array_diff($my_array,$my_elements);
$str_comp=implode(",", $result);
echo $str_comp;
输出:-
341,342,359