PHP检查如果某些键或值是一个多维数组 [英] PHP check if some keys or values are in a multidimensional array

查看:133
本文介绍了PHP检查如果某些键或值是一个多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想检查是否一个键/值是present某处阵列中的阵列结构。但我想使测试以这样的方式,我作出一个几乎镜像阵列验证

I have an array structure where I want to check if a key/value is present somewhere in the array. But I want to make the test in such a way that I make a an almost mirrored validation array.

可以说我有一个多维数组。这是我想验证数据。

Lets say I have a multidimensional array. This is the data I want to validate.

Array
(
[key1] => Array
    (
        [subkey1] => value
        [subkey2] => value
    )

[key2] => Array
    (
        [subkey3] => Array
            (
                [key1] => value
                [key2] => value
                [key3] => value
                [key4] => value
                [key5] => value
                [key6] => value
            )
    )
);

这是我的钥匙和价值观的需要是第一个阵列中的present数组。

And this is the array of my keys and values that need to be present in the first array.

Array
(
[key1] => Array
    (
        [subkey2] => value
    )

[key2] => Array
    (
        [subkey3] => Array
            (
                [key5] => value
                [key6] => value
            )
    )
);

我不能两个数组比较,因为他们永远不会是相同的。但我需要通过数据阵列以某种方式来运行和验证靠在验证阵列。两个键和值需要在适当的地点,关键需要相同的名称和值应是相同的为好。我只是不知道如何做一个像样的检查。我可以做一些递归检查?由于一些键可以是一个值,或者它需要检查这个问题,以及另一个阵列...这就是为什么我想递归,但我不知道如何使这一点。

I cant compare the two arrays because they will never be the same. But I need to run through the data array somehow and validate up against the validation array. Both the key and value need to be at the right place and the key need the same name and the value should be the same as well. I'm just not sure how to make a decent check. Can I make some recursive check? Since some of the keys can be a value or another array it needs to check for this as well... that's why I'm thinking recursive but I'm not sure how to make that.

希望能对你有所帮助。谢谢你。

Hope you can help. Thanks.

推荐答案

您可以使用它来确定递归所有需要的键是否present:

You could use this to recursively determine whether all required keys are present:

function has_recursive($data, $required)
{
    foreach ($required as $key => $value) {
        if (!isset($data[$key])/* && $data[$key] === $value */) {
            return false;
        }
        if (is_array($data[$key]) && false === has_recursive($data[$key], $value)) {
            return false;
        }
    }
    return true;
}

has_recursive($data, $required); // false or true

这篇关于PHP检查如果某些键或值是一个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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