this is the json that my code produces
{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555}
}
and this is the code
<?php
$c = array('a' => 11111, 'b' => 222222, 'c' => 33333, 'd' => 444454, 'e' => 55555555 );
$arr = array('aaa' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 , 'fff'=>$c);
echo json_encode($arr);
?>
but I want to have some structure like this
{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
"last":[
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}
I am new in json and php and I need this fast so I do not have time to read about this json structure... So please if someone know how to add this last element please provide some php code.
Thanks,
asked Nov 8, 2011 at 8:54
Lukap
32.1k65 gold badges162 silver badges245 bronze badges
1 Answer 1
- Take the "json-encoded" string and pass it to json_decode()
- assign the return value to a variable
- pass that variable to var_export() to get a "php-encoded" string representation of the data.
e.g.
<?php
$json = '{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
"last":[
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}';
$php = json_decode($json, true);
echo var_export($php);
prints
array (
'aaa' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'fff' =>
array (
'a' => 11111,
'b' => 222222,
'c' => 33333,
'd' => 444454,
'e' => 55555555,
),
'last' =>
array (
0 =>
array (
'id' => 8817,
'loc' => 'NEW YORK CITY',
),
1 =>
array (
'id' => 2873,
'loc' => 'UNITED STATES',
),
2 =>
array (
'id' => 1501,
'loc' => 'NEW YORK STATE',
),
),
)
answered Nov 8, 2011 at 8:58
VolkerK
96.3k20 gold badges169 silver badges232 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Damien
Damned, I was writing the resulting php code manualy! Clever use of var_export :-) Just to make the answer clearer, an array with not numeric keys is translated to an object (with {}) and a numeric keys array to an array (with []).
nickb
I do not understand how this answers the OP?
deceze
@Damien An array with continuous numeric keys.
array(1 => 'foo', 0 => 'bar') will be encoded as an object as well (at least in some versions of PHP, AFAIR).VolkerK
nickb, I assumed (wild-guessing-mode) the op had a some javascript object literal as a template and wanted a congruent php template. And via json_decode/var_export one can create such a php template. Not rocket science, but ...
lang-php
"last"array to your$arr?