验证阵列之间的键/值对 [英] Verifying key/value pairs between arrays

查看:105
本文介绍了验证阵列之间的键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大师阵列,和多个阵列我必须验证对主人。

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'];

目前我做的验证与此快件code的:

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

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

您已经可能注意到它会失败与 $ wrong_child_2 以上(未定义指数),虽然它不是在实际应用中的问题(至少目前如此)。

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).

我的问题是,会不会有更好的办法,使这些验证? preferably没有循环,而阵列功能。

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

推荐答案

有一个看的 和array_diff_assoc

Have a look at array_diff_assoc.

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

在换句话说, $ test_array 如果有任何差异,包括索引检查不验证。

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

这篇关于验证阵列之间的键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆