如何在数组中获取非重复元素?

时间:2017-10-04 09:31:10

标签: php arrays

   (
      "userServiceIds": "1,2,3",
      "enggServiceIds": "4,5,6,2,1",
   )

正如在这些数组中,我们只需要enggServiceIds只在userServiceIds

中不能重复的地方

正如我所要求的结果是: - 仅4,5,6

代码必须在PHP中运行

我试过这段代码

$input = array("$data[userServiceIds]" , "$data[enggServiceIds]");
            $result = implode(',',$input);
            $str = implode(',',array_unique(explode(',', $result)));

但结果是: - 1,2,3,4,5,6

正如我所要求的结果是: - 仅4,5,6

3 个答案:

答案 0 :(得分:2)

由于输入是JSON,首先将其转换为数组。然后使用array_diff     

$json = '{
  "userServiceIds": "1,2,3",
  "enggServiceIds": "4,5,6,2,1"
}';

$aData = json_decode($json, true);

$aResult = array_diff(explode(',',$aData['enggServiceIds']), explode(',',$aData['userServiceIds']));

print_r($aResult);

答案 1 :(得分:1)

阅读array_diff     

$userServiceIds = [1,2,3];
$enggServiceIds = [4,5,6,2,1];

var_dump(array_diff($enggServiceIds, $userServiceIds));

返回:

array(3) {
  [0]=>
  int(4)
  [1]=>
  int(5)
  [2]=>
  int(6)
}

live preview

答案 2 :(得分:1)

溶液:

$array1 = array(1,2,3);
$array2 = array(3,4,5,6);
$resultarray = array();
$resultarray = array_diff($array2, $array1);

结果:

Array ( [1] => 4 [2] => 5 [3] => 6 )