如何验证PHP数组的结构? [英] How can I validate the structure of my PHP arrays?

查看:226
本文介绍了如何验证PHP数组的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在确保所有给定数组符合特定结构的函数?我的意思是说它具有特定的键名,值的特定类型以及任何嵌套结构.

Is there a function out there to make sure that any given array conforms to a particular structure? What I mean is that is has particular key names, perhaps particular types for values, and whatever nested structure.

现在我有一个地方要确保经过的数组具有某些键,一对具有某种数据类型,以及一个具有特定键名的子数组.我做了很多尝试,因为我向它传递了格式错误的数组,最后我到了很多

Right now I have a place where I want to make sure that the array getting past has certain keys, a couple holding a certain data type, and one sub-array with particular key names. I've done a lot of run-around because I was passing malformed arrays to it, and finally I'm at the point where I have a bunch of

if ( ! isset($arr['key1']) ) { .... }
if ( ! isset($arr['key2']) ) { .... }
if ( ! isset($arr['key3']) ) { .... }

如果我可以事先检查数组是否符合特定的结构,我将节省很多时间和精力.理想情况是

I would have saved a lot of time and consternation if I could have checked that the array conformed to a particular structure beforehand. Ideally something like

$arrModel = array(
    'key1' => NULL ,
    'key2' => int ,
    'key3' => array(
        'key1' => NULL ,
        'key2' => NULL ,
      ),
);

if ( ! validate_array( $arrModel, $arrCandidate ) ) { ... }

那么,我要问的问题是,这是否已经存在,还是我自己写?

So, the question I'm asking is, does this already exists, or do I write this myself?

推荐答案

它不内置.

也许尝试类似(未经测试)的事情:

Maybe try something like (untested):

array_diff(array_merge_recursive($arrCandidate, $arrModel), $arrModel)

这篇关于如何验证PHP数组的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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