Array_diff in foreach?

假如想象 提交于 2019-12-25 17:08:26

问题


I need to compare values from some arrays. This array is multi dimensional and I need to compare the arrays inside.

Here the dump:

php

    array (size=4)
  1 => 
    array (size=3)
      0 => string '96' (length=2)
      1 => string '90' (length=2)
      2 => string '91' (length=2)
  2 => 
    array (size=3)
      0 => string '96' (length=2)
      1 => string '90' (length=2)
      2 => string '91' (length=2)
  3 => 
    array (size=4)
      0 => string '96' (length=2)
      1 => string '90' (length=2)
      2 => string '91' (length=2)
      3 => string '98' (length=2)
  4 => 
    array (size=4)
      0 => string '96' (length=2)
      1 => string '90' (length=2)
      2 => string '91' (length=2)
      3 => string '98' (length=2)

I wanted to use something like array_diff, to compare the different arrays but... even if it seems stupid, I don't know how to do it. I guess I expect to "extract" the 4 array, to be able to compare them.

Is there somebody that can explain me a good way to do this ? Thank you very much.


回答1:


<?php

$arr = [
    ['96','90','91'],
    ['96','90','91'],
    ['96','90','91','98'],
    ['96','90','91','98'],
];

$set = [];

foreach ($arr as $values) {
    foreach($values as $each_value){
        if(!isset($set[$each_value])) $set[$each_value] = true;
    }
}

$result = [];

$set = array_keys($set);

foreach ($arr as $values) {
    foreach($set as $value){
        if(!in_array($value,$values)) $result[] = $value;
    }
}

$result = array_unique($result);

print_r($result);

Demo: https://3v4l.org/gMZUR

  • We first make a set of elements to be present across each array.
  • Later, we move across all arrays once again and check each element in the set against each array values.
  • If we find an element in the set not present in any of the each individual sub arrays, we add it in the result.
  • Note that we can count frequency of element and compare it with the size of the actual data set, but duplicate values could cause issues.


来源:https://stackoverflow.com/questions/56771451/array-diff-in-foreach

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!