在数组内添加$ my_elements的问题

时间:2019-03-27 12:22:17

标签: php codeigniter

我的目的是减少与数字匹配的元素从一个数组到另一个数组。

$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;

3 个答案:

答案 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