Generate json string from multidimensional array data

Viewed 95903

I am using a plugin that requires an array of associative rows as a json formatted string -- something like:

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

How do I convert my multidimensional array to valid JSON output using PHP?

5 Answers

This is one of the most fundamental rules in php development:

DO NOT MANUALLY BUILD A JSON STRING. USE json_decode().

If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.

Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.

It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.

Code:

$array = [
    [
        'oV' => 'myfirstvalue',
        'oT' => 'myfirsttext'
    ],
    [
        'oV' => 'mysecondvalue',
        'oT' => 'mysecondtext'
    ]
];

echo json_encode($array);

Output:

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

For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.

You can use the stdClass, add the properties and json_encode the object.

$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;

echo '<pre>';var_dump( json_encode($object) , $object );die;

VoilĂ !

string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
  ["first_property"]=>
  int(1)
  ["second_property"]=>
  int(2)
}
Related