Array_diff在foreach? [英] Array_diff in foreach?

查看:99
本文介绍了Array_diff在foreach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较一些数组中的值。
这个数组是多维的,我需要比较内部数组。

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

在这里转储:


php

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)

我想使用之类的东西array_diff ,比较不同的数组,但是...即使看起来很愚蠢,我也不知道该怎么做。
我想我希望提取这4个数组,以便能够比较它们。

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.

推荐答案

<?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);

演示: 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.

这篇关于Array_diff在foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆