What is different between { and [ in json
model 1:
"cell": { "id": "3961" }
model 2:
"cell": [ "id": "3961" ]
how can i transfer model 1 to 2 via json_encode ?
{
is an Object, [
is an Array.
See the official Docs.
In your case, the first example is a normal Object with a property called id
. The second example is an associative array with an index called id
. JSON does not have associative arrays. The second example is invalid JSON.
This is, due to the fact that JSON is JavaScript Object Notification and JavaScript does not know associative arrays. Instead, JavaScript allows you to dynamically add new property to an Object and enables you to access any Object-property using the brackets: Object['property']
.
So, Objects are (kind of) associative arrays in JavaScript and therefor in JSON.
Since the json_encode()
-function encodes creates the JSON-String from the supplied object, you'll need to pass an object instead of an array.
php > echo json_encode(array('a', 'b'));
["a","b"]
php > echo json_encode(array('a' => 'A', 'b' => 'B'));
{"a":"A","b":"B"}
[ -> Numeric array
{ -> Associative array in PHP, Object in JavaScript
"model 2" is not valid JSON. JSON allows for objects with named properties (your "model 1"), but arrays may not have named keys.
Therefore, json_encode
cannot output your "model 2".
Your model 2 is not valid JSON. JSON arrays cannot contain keys, that's what objects are for in JavaScript ({"key":"value"}
)
You can, however, decode a JSON string into PHP's associative arrays (json_decode($json, TRUE)
) if you want to create arrays instead of objects.