我正在使用一个API,要求以特定方式格式化JSON。简化用于显示目的。
我需要知道如何通过php执行此操作,我目前正在使用一堆嵌套的array()
,然后在该数组值上使用json_encode()
。
来自json_encode($data);
JSON格式正在发生
{
"value1": "1",
"value2": "2",
"value3": "3",
"value4":
{
"value4a":
{
"value4aa": "1",
"value4ab": {
"value4aba": {
"value4abaa": "1",
"value4abab": "2",
"value4abac": "3",
"value4abad": "4"
}
}
}
,
"value4b": {
"value4ba": "1",
"value4bb": "2",
"value4bc": "3"
}
}
}
这就是我想要的东西
{
"value1": "1",
"value2": "2",
"value3": "3",
"value4": [
{
"value4a": [
{
"value4aa": "1",
"value4ab": {
"value4aba": [
{
"value4abaa": "1",
"value4abab": "2",
"value4abac": "3",
"value4abad": "4"
}
]
}
}
],
"value4b": {
"value4ba": "1",
"value4bb": "2",
"value4bc": "3"
}
}
]
}
我在网上看到的任何地方我默认会看到方括号回来,但我只需要在特定的数组中。我不确定如何提出这个问题,所以我提前为缺乏信息或可能的愚蠢问题而道歉。
答案 0 :(得分:0)
我用json_decode来看看php需要构建你的json。 这就是我得到的:
stdClass Object
(
[value1] => 1
[value2] => 2
[value3] => 3
[value4] => Array
(
[0] => stdClass Object
(
[value4a] => Array
(
[0] => stdClass Object
(
[value4aa] => 1
[value4ab] => stdClass Object
(
[value4aba] => Array
(
[0] => stdClass Object
(
[value4abaa] => 1
[value4abab] => 2
[value4abac] => 3
[value4abad] => 4
)
)
)
)
)
[value4b] => stdClass Object
(
[value4ba] => 1
[value4bb] => 2
[value4bc] => 3
)
)
)
)
这就是构建你的json的代码: (用http://writecodeonline.com/php/测试)
$o = new stdClass();
$o->value1 = "1";
$o->value2 = "2";
$o->value3 = "3";
$o->value4 = array();
$o->value4[0] = new stdClass();
$o->value4[0]->value4a = array();
$o->value4[0]->value4a[0] = new stdClass();
$o->value4[0]->value4a[0]->value4aa = "1";
$o->value4[0]->value4a[0]->value4ab = new stdClass();
$o->value4[0]->value4a[0]->value4ab->value4aba = array();
$o->value4[0]->value4a[0]->value4ab->value4aba[0] = new stdClass();
$o->value4[0]->value4a[0]->value4ab->value4aba[0]->value4abaa = "1";
$o->value4[0]->value4a[0]->value4ab->value4aba[0]->value4abab = "2";
$o->value4[0]->value4a[0]->value4ab->value4aba[0]->value4abac = "3";
$o->value4[0]->value4a[0]->value4ab->value4aba[0]->value4abad = "4";
$o->value4[0]->value4b = new stdClass();
$o->value4[0]->value4b->value4ba = "1";
$o->value4[0]->value4b->value4bb = "2";
$o->value4[0]->value4b->value4bc = "3";
$json = json_encode($o);
使其更具动态性,例如,在for循环中,您可以这样使用它:
$num = "1";
$o->{"value$num"} = $num;