比较具有不同数量元素的两个多维数组

时间:2014-05-30 01:58:31

标签: php multidimensional-array

我有两个具有不同数量元素的多维数组:

$complete = array(array("24","G:\TVShows\24"),array("Lost","G:\TVShows\Lost"),array("Game of Thrones","G:\TVShows\Game of Thrones"));
$subset = array(array("24","G:\TVShows\24","English"));

第一个($ complete)是我在磁盘上的电视节目的完整列表(节目名称,文件路径)。第二个($ subset)来自我的数据库,并将口语作为第三列/元素包含在内。

我想返回我在磁盘上但没有出现在数据库中的节目。如何将这些元素与具有不同元素数量的数组进行比较?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于它是一个多级数组,您可以使用并组合array_map()serialize()/unserialize()。考虑这个例子:

$complete = array(
    array("24","G:\TVShows\24"),
    array("Lost","G:\TVShows\Lost"),
    array("Game of Thrones","G:\TVShows\Game of Thrones"),
    array("The Walking Dead","G:\TVShows\The Walking Dead"),
    array("Breaking Bad","G:\TVShows\Breaking Bad"),
    array("Heroes","G:\TVShows\Heroes"),
);

$subset = array(
    array("24","G:\TVShows\24","English"),
    array("The Walking Dead","G:\TVShows\The Walking Dead","English"),
    array("Heroes","G:\TVShows\Heroes","English"),
);

$shows_not_in_db = array();
// properly format the subsets for comparison on complete
foreach($subset as $key_s => $value_s) {
    array_pop($value_s); // remove the last element "English"
    $subset[$key_s] = serialize($value_s);
}

// serialize each complete arrays
$complete = array_map('serialize', $complete);
$shows_not_in_db = array_map('unserialize', array_diff($complete, $subset)); // array diff them, then unserialize

print_r($shows_not_in_db);

Sample Output

  

编辑:对于不区分大小写的比较,您可以使用此替代方法:

$shows_not_in_db = array_map('unserialize', array_udiff($complete, $subset, 'strcasecmp'));

// sample: The walking dead - The Walking Dead