如何在没有密钥的情况下将JSON数据转换为数组?

时间:2016-04-09 05:45:49

标签: php json php-7

我有一组JSON规则,我试图将其转换为PHP数组。

这是一套规则:

{
"rules" : {
    "full_name" : "required",
    "email" : {
        "required" : true,
        "email" : true
    },
    "phone" : {
        "required" : true,
        "maxlength" : 10
    },
    "comments" : {
        "minlength" : 10
    }
}
}

这是我正在努力的最终结果:

        $rules = [
        'full_name' =>  'required',
        'email'     =>  [ 'required', 'email'],
        'phone'     =>  [ 'max_length' => 10 ],
        'message'   =>  [ 'min_length' => 10 ]
    ];

我创建了这个在json_decode:

之后读取json数据的转换方法
 private function convertRules($rules)
{
    $convertedRules = [];

    foreach( $rules as $key => $value ) {

        if( is_array($value)) {

            $value = $this->convertRules($value);
        }

        switch( $key ) {

            case '1':

                $value = $key;

                break;

            case 'minlength':

                $key = 'min_length';

                break;

            case 'maxlength':

                $key = 'max_length';

                break;
        }

        switch( $value ) {

            case '1':

                $value = $key;

                break;
        }

        $convertedRules[$key] = $value;
    }


    return $convertedRules;
}

但是它会创建一个包含复制值的键的数组。

    Array
(
    [full_name] => required
    [email] => Array
        (
            [required] => required
            [email] => email
        )

    [phone] => Array
        (
            [required] => required
            [max_length] => 10
        )

    [comments] => Array
        (
            [min_length] => 10
        )

)

如何在没有与上面的PHP规则数组类似的键的情况下获取数组?

任何PHP7优化也值得赞赏!

1 个答案:

答案 0 :(得分:1)

您可以调整convert_rules函数以产生所需的结果,如下所示:

function convert_rules($rules) {
    $result = [];

    foreach ($rules as $name => $ruleSet) {
        if (!is_array($ruleSet)) {
            $result[$name] = $ruleSet;
        } else {
            $result[$name] = [];

            foreach ($ruleSet as $rule => $value) {
                switch ($rule) {
                    case 'maxlength':
                        $result[$name]['max_length'] = $value;
                        break;

                    case 'minlength':
                        $result[$name]['min_length'] = $value;
                        break;

                    default:
                        $result[$name][] = $rule;
                }
            }
        }
    }

    return $result;
}

如您所见,默认行为是插入没有键的规则。对于其他任何事情,只需创建一个单独的case