0

I have the following array called $submissions:

Array ( [0] => 342 [1] => 343 [2] => 344 [3] => 345 )

I then have a string:

$in_both = 342,344;

I then am using this code to remove any number thats in $in_both from $submissions:

if(($key = array_search($in_both, $submissions)) !== false) {
    unset($submissions[$key]);
}

The problem is this is only working for the first number.

How can I have all the numbers removed from the array that are in the variable $in_both?

Thank you

4

4 回答 4

2

由于in_both是字符串,所以需要将其转换为数组:

$in_both_arr = explode(",",$in_both);

然后你可以比较数组:

$submissions = array_diff($submissions,$in_both_arr);

请参阅文档

于 2013-09-26T09:35:10.480 回答
1

尝试这个:

$submissions = Array( 342, 343, 344, 345 );

$in_both = '342,344';

$needles = explode(',', $in_both);
foreach ($needles as $needle) {
    while (($key = array_search($needle, $submissions)) !== false) {
        unset($submissions[$key]);
    }
}

foreach 中的 while 保证数组中每次出现的数字都将被删除。

于 2013-09-26T09:42:10.940 回答
0

尝试:

$submissions = array(342, 343, 344, 355);
$in_both     = '342,344';

foreach ( explode(',', $in_both) as $value ) {
  if(($key = array_search($value, $submissions)) !== false) {
    unset($submissions[$key]);
  }
}
于 2013-09-26T09:35:19.057 回答
0

您必须使用expolde 带有“,”分隔符的函数,并循环通过explode如下创建的数组

$in_both = "342,344";
$in_both_arr = explode(",",$in_both);
foreach($in_both_arr as $val)
   if(($key = array_search($val, $submissions)) !== false) {
    unset($submissions[$key]);
   }
}
于 2013-09-26T09:39:31.390 回答