简体   繁体   中英

Json array of objects in php

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,

  • 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.

eg

<?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',
    ),
  ),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM