Generate json string from multidimensional array data [duplicate]

Once you have your PHP data, you can use the json_encode function; it’s bundled with PHP since PHP 5.2.

In your case, your JSON string represents:

  • a list containing 2 elements
  • each one being an object, containing 2 properties/values

In PHP, this would create the structure you are representing:

$data = array(
    (object)array(
        'oV' => 'myfirstvalue',
        'oT' => 'myfirsttext',
    ),
    (object)array(
        'oV' => 'mysecondvalue',
        'oT' => 'mysecondtext',
    ),
);
var_dump($data);

The var_dump gets you:

array
  0 => 
    object(stdClass)[1]
      public 'oV' => string 'myfirstvalue' (length=12)
      public 'oT' => string 'myfirsttext' (length=11)
  1 => 
    object(stdClass)[2]
      public 'oV' => string 'mysecondvalue' (length=13)
      public 'oT' => string 'mysecondtext' (length=12)

And, encoding it to JSON:

$json = json_encode($data);
echo $json;

You get:

[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]

By the way, from what I remember, I’d say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects’ properties.

See http://www.json.org/ for the grammar.

Leave a Comment