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?

0

5 Answers 5

70

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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"}]
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', ), );
Oh, yes, I'm using the 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)
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.

3 Comments

This worked like a charm thank you. Although if I understand correctly I should have used "json_encode" would have been better coding?
@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).
I recently wrote a PHP JSON Builder which allows to build JSON programmatically: github.com/borisguery/json-builder
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.

Comments

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)
}

1 Comment

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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.