I'm working with an API that requires JSON to be formatted a specific way. Simplified for display purposes.
I need to know how to do this via php, I'm currently using a bunch of nested array()
's and then using json_encode()
on that array value.
from json_encode($data);
JSON Formatting that's happening
{
"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"
}
}
}
Here's what I want
{
"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"
}
}
]
}
Everywhere I've looked online I see square brackets coming back by default, but I only need them in specific arrays. I'm not sure exactly how to ask this question, so I apologize in advance for the lack of information or possible stupid question.
I used json_decode to take a look at what php needs to build your json. This is what i got:
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
)
)
)
)
And this ist the code to build your json: (tested with 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);
to make it more dynamic, in a for loop for example, you can use it this way:
$num = "1";
$o->{"value$num"} = $num;