Array_diff in foreach?

2019-09-19 19:41发布

问题:

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.


标签: php loops diff