将多维数组与多维对象数组进行比较

时间:2016-05-24 05:23:51

标签: php arrays multidimensional-array

我有两个数组,我想从中提取匹配并返回它们。第一个数组是我的查询数组,如果你想调用它,第二个数组就是各种数据库。考虑到这一点,因为我和PHP一样生锈,我试图找出如何以尽可能少的开销循环这些,同时只从第二个返回唯一匹配的整个对象。用php做一个干净的方法吗?如果是这样的话,任何人都可以帮我指点一般方向。

首先

[
   ["something", "domain.com"],
   ["something1", "sub.domain.com"]
]

第二

[
{
   "id": "abcde12345",
   "name": "Company Name",
   "corp_name": [
     "Company, Inc.",
     "Company Inc."
   ],
   "_names": [],
   "_products": [],
   "urls": [
      "www.domain.com",
      "domain.com",
      "sub.domain.com"
   ]
},
{
   "id": "abcde12345",
   "name": "Company Name",
   "corp_name": [
     "Company, Inc.",
     "Company Inc."
   ],
   "_names": [],
   "_products": [],
   "urls": [
      "www.domain.com",
      "domain.com",
      "sub.domain.com"
   ]
}.
{
   "id": "abcde12345",
   "name": "Company Name",
   "corp_name": [
     "Company, Inc.",
     "Company Inc."
   ],
   "_names": [],
   "_products": [],
   "urls": [
      "www.domain.com",
      "domain.com",
      "sub.domain.com"
   ]
}
]

1 个答案:

答案 0 :(得分:1)

这里是比较数组的功能

http://php.net/manual/en/function.array-diff-assoc.php

在下面的评论中,有一个递归版本。我允许自己在这里粘贴一份。

<?php
function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}
?>