Php多维搜索数组键和值匹配语言对

时间:2016-04-28 12:23:29

标签: php arrays multidimensional-array

在php中我有两个像这样的数组

    $array1 = 
Array
(
    [0] => Array
        (
            [source_language] => Arabic
            [target_language] => Array
                (
                    [0] => Assamese
                    [1] => Azerbaijani
                )

        )
    [1] => Array
        (
            [source_language] => Azerbaijani
            [target_language] => Array
                (
                    [0] => Burmese
                    [1] => Korean
                )

        )        

)

$array2 = 
Array
(
    [1] => Array
        (
            [source_language] => English
            [target_language] => Array
                (
                    [0] => German
                    [1] => Norwegian
                )

        )

    [2] => Array
        (
            [source_language] => Azerbaijani
            [target_language] => Array
                (
                    [0] => Burmese
                    [1] => Korean
                )

        )

    [3] => Array
        (
            [source_language] => Azerbaijani
            [target_language] => Array
                (
                    [0] => Kazakh
                    [1] => Maithili
                    [2] => Uzbek
                )

        )

)

我想在array2中搜索array1的所有值。所以基本上它将做的是 它将搜索array2中的array1源和语言对值。并返回这些值 哪个不匹配

作为参考,你可以在array1中看到我们有数组块元素

  [1] => Array
        (
            [source_language] => Azerbaijani
            [target_language] => Array
                (
                    [0] => Burmese
                    [1] => Korean
                )

        )

在array2中具有相同的值。但

没有匹配
  [0] => Array
        (
            [source_language] => Arabic
            [target_language] => Array
                (
                    [0] => Assamese
                    [1] => Azerbaijani
                )

        )
在array2中的

所以它应该返回错误,就像那些给定的具有源语言和目标语言名称的对没有源语言和目标语言一样。那么有人能告诉我这是怎么做到的吗?

输出应显示在array2中不匹配的所有数组。所以这里它应该返回这个数组

[0] => Array
        (
            [source_language] => Arabic
            [target_language] => Array
                (
                    [0] => Assamese
                    [1] => Azerbaijani
                )

        )

更新

我已经尝试过array_merge这两个数组,之后我使用了array_diff($array1, $merged_array) 但仍然无法正常工作。

1 个答案:

答案 0 :(得分:0)

<强>更新

出于某种原因,array_udiff在PHP5和PHP7中返回不同的结果。我们可以使用foreach然后=)

$diff = [];

foreach ($array1 as $a1) {
  $h1 = md5(json_encode($a1));
  $found = false;

  foreach ($array2 as $a2) {
    if (md5(json_encode($a2)) == $h1) {
      $found = true;
      break;
    }
  }

  if (!$found) {
    $diff []= $a1;
  }
}

原始回答

$diff = array_udiff($array1, $array2, function ($a, $b) {
  return md5(json_encode($a)) == md5(json_encode($b)) ? 0 : 1;
});