douwen9343 2014-05-30 01:58
浏览 71
已采纳

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

I have two multidimensional arrays with different number of elements:

$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"));

The first one ($complete) is the complete list of my tv shows on disk (name of the show, path to files). The second one ($subset) come from my database and include the spoken language as a third column / element.

I would like to return the shows that I have on disk but that do not appear in databse. How can I compare those to array with different number of elements?

Thank you for your help!

  • 写回答

1条回答 默认 最新

  • douzheng9221 2014-05-30 03:18
    关注

    Since its a multi leveled array, you could use and combine array_map() and serialize()/unserialize(). Consider this example:

    $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

    Edit: For case insensitive comparisons, you may use this alternative:

    $shows_not_in_db = array_map('unserialize', array_udiff($complete, $subset, 'strcasecmp'));
    
    // sample: The walking dead - The Walking Dead
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?