32

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Haluk
  • 2,091
  • 2
  • 27
  • 35

5 Answers5

69

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • 2
    You don't actually need to cast arrays into objects. json_encode will automagically figure it should represent things as an object if you have string keys. – Jani Hartikainen Sep 16 '09 at 20:04
  • 1
    Hi, The output I got from the above code is actually different: array(2) { [0]=> object(stdClass)#1 (2) { ["oV"]=> string(12) "myfirstvalue" ["oT"]=> string(11) "myfirsttext" } [1]=> object(stdClass)#2 (2) { ["oV"]=> string(13) "mysecondvalue" ["oT"]=> string(12) "mysecondtext" } } [{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}] – Haluk Sep 16 '09 at 20:18
  • 1
    I removed the var_dump from the above code and modified the main part as follows. Now it works fine: $data = array( array( oV => 'myfirstvalue', oT => 'myfirsttext', ), array( oV => 'mysecondvalue', oT => 'mysecondtext', ), ); – Haluk Sep 16 '09 at 20:26
  • Oh, yes, I'm using the http://xdebug.org/ extension, so my var_dump is a bit different from the default one (better html-formated output ; ie, easier to debug) ;; about the cast to object : it's not necessary, but I like having them, to get objects on the PHP side too, and not only on the JSON/javascript side (I feel better having datatypes that are close on both sides) – Pascal MARTIN Sep 16 '09 at 20:30
16

The simplest way would probably be to start with an associative array of the pairs you want:

$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");

then use a foreach and some string concatenation:

$jsontext = "[";
foreach($data as $key => $value) {
    $jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";

Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • This worked like a charm thank you. Although if I understand correctly I should have used "json_encode" would have been better coding? – Haluk Sep 16 '09 at 20:13
  • @TimWachter This answer is from 2009; note the bit at the end about "if you have a recent version"; a fair number of hosts were still running only PHP 4 (and `json_encode` was introduced in 5.2). – Amber Apr 13 '14 at 05:38
  • I recently wrote a PHP JSON Builder which allows to build JSON programmatically: https://github.com/borisguery/json-builder – Boris Guéry Jan 13 '15 at 09:31
2

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
1

This is the php code to generate json format.

while ($row=mysqli_fetch_assoc($result))
{
    $array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
MashukKhan
  • 1,946
  • 1
  • 27
  • 46
1

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)
}
sbaan da
  • 11
  • 3
  • It would not matter if the data type of the input was an an array or an object -- `json_encode()` will generate the exact same string. – mickmackusa Aug 03 '21 at 10:04