通过PHP进行JSON格式转换

时间:2018-02-14 09:32:01

标签: php arrays json

我有一个json格式,并希望将其转换为我的自定义格式。我想用PHP进行这种转换。如何构造上述JSON数组格式。我想放置" id"的重复值。在数组中验证不同,这是我的格式:

[{
"id": "1",
"label": "Username",
"type": "email",
"sequence": "1",
"field_name": "af1",
"group_name": "login",
"validation_name": "required",
"validation_message": "Please fill out this field."
}, {
"id": "2",
"label": "Password",
"type": "password",
"sequence": "2",
"field_name": "af2",
"group_name": "login",
"validation_name": "required",
"validation_message": "Please fill out this field."
}, {
"id": "3",
"label": "Mobile",
"type": "text",
"sequence": "3",
"field_name": "af3",
"group_name": "educational",
"validation_name": "required",
"validation_message": "Please fill out this field."
 }, {
"id": "1",
"label": "Username",
"type": "email",
"sequence": "1",
"field_name": "af1",
"group_name": "login",
"validation_name": "data-minlength",
"validation_message": "Minimum of 6 characters"
}]

我想要这个:

[{
"id": "1",
"label": "Username",
"type": "email",
"sequence": "1",
"field_name": "af1",
"group_name": "login",
"validation": [{
        "validation_name": "required",
        "validation_message": "Please fill out this field."
    },
    {
        "validation_name": "data-minlength",
        "validation_message": "Minimum of 6 characters"
    }
]

}, {
"id": "2",
"label": "Password",
"type": "password",
"sequence": "2",
"field_name": "af2",
"group_name": "login",
"validation": [{
    "validation_name": "required",
    "validation_message": "Please fill out this field."
}]
}, {
"id": "3",
"label": "Mobile",
"type": "text",
"sequence": "3",
"field_name": "af3",
"group_name": "educational",
"validation": [{
    "validation_name": "required",
    "validation_message": "Please fill out this field."
}]
}]

1 个答案:

答案 0 :(得分:0)

我确定您的问题出现在生成json的代码中。

但是如果你仍然想这样做,你可以注册/保存已经处理成$ var

的id
<?php
$json = '[{
"id": "1",
"label": "Username",
"type": "email",
"sequence": "1",
"field_name": "af1",
"group_name": "login",
"validation_name": "required",
"validation_message": "Please fill out this field."
}, {
"id": "2",
"label": "Password",
"type": "password",
"sequence": "2",
"field_name": "af2",
"group_name": "login",
"validation_name": "required",
"validation_message": "Please fill out this field."
}, {
"id": "3",
"label": "Mobile",
"type": "text",
"sequence": "3",
"field_name": "af3",
"group_name": "educational",
"validation_name": "required",
"validation_message": "Please fill out this field."
 }, {
"id": "1",
"label": "Username",
"type": "email",
"sequence": "1",
"field_name": "af1",
"group_name": "login",
"validation_name": "data-minlength",
"validation_message": "Minimum of 6 characters"
}]';
$array = json_decode($json);
$temp = array();
$newArray= array();
foreach($array as $key){
    if(!    in_array($key->id, $temp)){
        $temp[]=$key->id;
        $newArray[] = $key;
    }
}
echo json_encode($newArray);