PHP对象模式验证

时间:2014-07-08 16:17:21

标签: php json object recursion

是否可以动态检查两个对象架构是否相同(在php中)?例如:

{
   name: "Name1",
   age: 2,
   kids: [1,3,4]
}

{
   name: "Name2",
   age: 2,
   kids: [1,6,4,3]
}

对于上面的例子,我希望返回true。这是另一个例子:

{
   name: "Name1",
   age: 2,
   kids: [1,3,4]
}

{
   name: "Name1",
   kids: [1,3,4]
}

这里我希望得到假(架构不一样:第二个对象缺少年龄)。

函数定义应如下所示:Boolean isSchemaEqual($obj1, $obj2)(我知道php中没有函数定义,只是为了让我的问题更清楚)。

注意:架构可以嵌套,因为我的意思是某些属性可以容纳一个对象,该对象也需要针对其他对象的(相同)属性进行检查。

2 个答案:

答案 0 :(得分:1)

如果您希望验证多个模式级别,可以将递归与密钥的无顺序数组比较习惯用法结合使用。

// determines if an array is associative
function isAssociative($array) {
    return (bool)count(array_filter(array_keys($array), 'is_string'));
}

// determines if the keys of two arrays are equal regardless of order
function keysEqual($a, $b) {
    if (!is_array($a) || !is_array($b))
        return false;

    $keysA = array_keys($a);
    $keysB = array_keys($b);

    return array_diff($keysA, $keysB) === array_diff($keysB, $keysA);
}

function isSchemaEqual($a, $b) {
    // validate keys - basic validation
    if (!keysEqual($a, $b))
        return false;

    // if we come across any key where the value is associative and 
    // the schema isn't the same for b's value at $key, then we know 
    // the schemas aren't equal 
    foreach ($a as $key => $value) {
        if (is_array($value) && isAssociative($value) && !isSchemaEqual($value, $b[$key]))
            return false;
    }

    // we couldn't find any differences, so they're equal
    return true;
}

您可以找到一些测试 here

答案 1 :(得分:0)

比较键:

if (array_keys($schema1) == array_keys($schema2)) {

}

对于嵌套对象,您必须自己创建函数。一种方法是将其设置为一级,使{kids: {boys: [1,2,3]}}之类的路径成为kids/boys,然后您可以比较数组:

function flatten_keys($object, $prefix = '') {
   $result = array();
   foreach ($object as $key=>$value) {
     $result[] = $prefix . $key;
     if (is_object($value) || (is_array($value) && array_values($value) != $value) ) {
         $result = array_merge($result, flatten_keys($value, $key .'/'));
     }
   }
   return $result;
}

$a = flatten_keys($schema2);
$b = flatten_keys($schema2);
sort($a);
sort($b);
if ($a == $b){

}