如何在php中比较2D数组中的元素


How to compare the elements in 2D array in php

嗨,我有一个这样的数组。。。

array(
   array(
      1, 3
   ),
   array(
      4, 6, 8
   ),
   array(
      2, 3, 5, 1
   )
)

现在我想将第一个元素与第二行中的所有元素进行比较。意思是我想将1与4、6和8进行比较。然后与第三行元素(如1与2、3、5和1)进行比较。同样,我想比较

1在给定的数组中总共存在两次。。。。所以变量count1=2……同样3存在2次,所以count2=2…8只存在一次,所以count8=1……像这样。。。

请帮我解决这个问题。提前谢谢。

如果您正在查找频率表,可以使用array_merge()将其压平,然后使用array_count_values()来获得计数:

print_r(array_count_values(call_user_func_array('array_merge', $array)));

输出:

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

检查此答案

或示例

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

使用

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';