dongzhi6087 2010-10-27 19:04
浏览 97
已采纳

如何验证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?

  • 写回答

5条回答 默认 最新

  • dongzhentiao2326 2010-10-27 19:24
    关注

    It doesn't exist built in.

    Maybe try something like (untested):

    array_diff(array_merge_recursive($arrCandidate, $arrModel), $arrModel)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答