dongzhiqi0332 2014-05-16 04:25
浏览 37
已采纳

验证数组之间的键/值对

I have a "master" array, and several arrays I have to verify against the master.

The master array is a list of key/value pairs. The other arrays have to be made of some (or all) of these pairs, nothing else.

Here is some example to clarify:

$master = [1=>'foo', 2=>'bar', 3=>'baz'];
$good_child = [2=>'bar'];
$wrong_child_1 = [2=>'sparta'];
$wrong_child_2 = [42=>'bar'];

Currently I'm doing the verification with this quick piece of code:

foreach ($child as $key => $value) {
    if ($master[$key] !== $value) {
        // wrong child
    }
}

You already may have noticed it would fail with the $wrong_child_2 above (undefined index), although it's not a problem in the real application (at least for now).

My question is, would there be a better way to make these verifications? Preferably without loops, rather array functions.

  • 写回答

1条回答 默认 最新

  • duandan4680 2014-05-16 04:41
    关注

    Have a look at array_diff_assoc.

    $bad = (bool)count(array_diff_assoc($test_array, $master_array))
    

    In other words, $test_array does not validate if there are any differences, including the index check.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程