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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With