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,

Answers


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

Need Your Help

returning a lambda without std::function

c++ c++11 lambda return-type higher-order-functions

Consider the following function which is returning a lambda:

Optimize search to find next matching value in a list

python bigdata

I have a program that goes through a list and for each objects finds the next instance that has a matching value. When it does it prints out the location of each objects. The program runs perfectly...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.