Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode PHP array as JSON array not JSON object

Tags:

json

php

People also ask

What does the PHP function json_encode () do?

PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.

Which function in PHP can be used to convert objects in PHP into JSON?

json_encode() is a native PHP function that allows you to convert PHP data into the JSON format. The function takes in a PHP object ($value) and returns a JSON string (or False if the operation fails).

Can you convert array to JSON?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

What is the difference between json_encode and json_decode?

PHP json_decode() and json_encode(): Summary JSON can be handled by using inbuilt PHP functions. For example, a PHP object might be turned into JSON format file using PHP json_encode() function. For the opposite transformation, use PHP json_decode() . PHP arrays are not supported by XML but can be converted into JSON.


See Arrays in RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format:

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

You are observing this behaviour because your array is not sequential - it has keys 0 and 2, but doesn't have 1 as a key.

Just having numeric indexes isn't enough. json_encode will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

json_decode($jsondata, true);

true turns all properties to array (sequential or not)