How to create an array for JSON using PHP?
In this article, we will see how to create an array for the JSON in PHP, & will see its implementation through examples.
Array: Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. An array is created using an array() function in PHP. There are 3 types of array in PHP that are listed below:
- Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value.
- Associative Array: It is used to store key-value pairs.
- Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays.
For this purpose, we will use an associative array that uses a key-value type structure for storing data. These keys will be a string or an integer which will be used as an index to search the corresponding value in the array. The json_encode() function is used to convert the value of the array into JSON. This function is added in from PHP5. Also, you can make more nesting of arrays as per your requirement. You can also create an array of array of objects with this function. As in JSON, everything is stored as a key-value pair we will convert these key-value pairs of PHP arrays to JSON which can be used to send the response from the REST API server.
Example 1: The below example is to convert an array into JSON.
json_decode
Takes a JSON encoded string and converts it into a PHP value.
Parameters
The json string being decoded.
This function only works with UTF-8 encoded strings.
Note:
PHP implements a superset of JSON as specified in the original » RFC 7159.
When true , JSON objects will be returned as associative array s; when false , JSON objects will be returned as object s. When null , JSON objects will be returned as associative array s or object s depending on whether JSON_OBJECT_AS_ARRAY is set in the flags .
Maximum nesting depth of the structure being decoded. The value must be greater than 0 , and less than or equal to 2147483647 .
Bitmask of JSON_BIGINT_AS_STRING , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_OBJECT_AS_ARRAY , JSON_THROW_ON_ERROR . The behaviour of these constants is described on the JSON constants page.
Return Values
Returns the value encoded in json in appropriate PHP type. Values true , false and null are returned as true , false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.
Errors/Exceptions
If depth is outside the allowed range, a ValueError is thrown as of PHP 8.0.0, while previously, an error of level E_WARNING was raised.
Changelog
Version | Description |
---|---|
7.3.0 | JSON_THROW_ON_ERROR flags was added. |
7.2.0 | associative is nullable now. |
7.2.0 | JSON_INVALID_UTF8_IGNORE , and JSON_INVALID_UTF8_SUBSTITUTE flags were added. |
7.1.0 | An empty JSON key («») can be encoded to the empty object property instead of using a key with value _empty_ . |
Examples
Example #1 json_decode() examples
var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , true ));
The above example will output:
object(stdClass)#1 (5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) > array(5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) >
Example #2 Accessing invalid object properties
Accessing elements within an object that contain characters not permitted under PHP’s naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.
$obj = json_decode ( $json );
print $obj ->< 'foo-bar' >; // 12345
Example #3 common mistakes using json_decode()
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = «< 'bar': 'baz' >» ;
json_decode ( $bad_json ); // null
// the name must be enclosed in double quotes
$bad_json = ‘< bar: "baz" >‘ ;
json_decode ( $bad_json ); // null
// trailing commas are not allowed
$bad_json = ‘< bar: "baz", >‘ ;
json_decode ( $bad_json ); // null
Example #4 depth errors
// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode (
array(
1 => array(
‘English’ => array(
‘One’ ,
‘January’
),
‘French’ => array(
‘Une’ ,
‘Janvier’
)
)
)
);
?php
// Show the errors for different depths.
var_dump ( json_decode ( $json , true , 4 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
var_dump ( json_decode ( $json , true , 3 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
?>
The above example will output:
array(1) < [1]=>array(2) < ["English"]=>array(2) < [0]=>string(3) "One" [1]=> string(7) "January" > ["French"]=> array(2) < [0]=>string(3) "Une" [1]=> string(7) "Janvier" > > > Last error: No error NULL Last error: Maximum stack depth exceeded
Example #5 json_decode() of large integers
var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , false , 512 , JSON_BIGINT_AS_STRING ));
The above example will output:
object(stdClass)#1 (1) < ["number"]=>float(1.2345678901235E+19) > object(stdClass)#1 (1) < ["number"]=>string(20) "12345678901234567890" >
Notes
Note:
The JSON spec is not JavaScript, but a subset of JavaScript.
Note:
In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
See Also
User Contributed Notes 8 notes
JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a «list» or «object» when converted to/from JSON, depending on the keys (of absence of them).
You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:
$json = »;
$array = json_decode($json, true); // decode as associative hash
print json_encode($array) . PHP_EOL;
This will output a different JSON string than the original:
The object has turned into an array!
Similarly, a array that doesn’t have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.
$array = [
‘first’,
‘second’,
‘third’,
];
print json_encode($array) . PHP_EOL;
// remove the second element
unset($array[1]);
print json_encode($array) . PHP_EOL;
The array has turned into an object!
In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!
On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.
Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.
If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:
If you want to enforce an array to encode to a JSON object, use:
json_encode
Возвращает строку, содержащую JSON-представление для указанного value . Если параметр является массивом ( array ) или объектом ( object ), он будет рекурсивно сериализован.
Если сериализуемое значение является объектом, то по умолчанию будут включены только публично видимые свойства. В качестве альтернативы класс может реализовать интерфейс JsonSerializable для управления тем, как его значения сериализуются в JSON .
На кодирование влияет параметр flags и, кроме того, кодирование значений типа float зависит от значения serialize_precision.
Список параметров
value — значение, которое будет закодировано. Может быть любого типа, кроме resource.
Функция работает только с кодировкой UTF-8.
Замечание:
PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.
Битовая маска, составляемая из значений JSON_FORCE_OBJECT , JSON_HEX_QUOT , JSON_HEX_TAG , JSON_HEX_AMP , JSON_HEX_APOS , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_NUMERIC_CHECK , JSON_PARTIAL_OUTPUT_ON_ERROR , JSON_PRESERVE_ZERO_FRACTION , JSON_PRETTY_PRINT , JSON_UNESCAPED_LINE_TERMINATORS , JSON_UNESCAPED_SLASHES , JSON_UNESCAPED_UNICODE , JSON_THROW_ON_ERROR . Смысл этих констант объясняется на странице JSON-констант.
Устанавливает максимальную глубину. Должен быть больше нуля.
Возвращаемые значения
Возвращает строку ( string ), закодированную JSON или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Добавлена константа JSON_THROW_ON_ERROR для параметра flags . |
7.2.0 | Добавлены константы JSON_INVALID_UTF8_IGNORE и JSON_INVALID_UTF8_SUBSTITUTE для параметра flags . |
7.1.0 | Добавлена константа JSON_UNESCAPED_LINE_TERMINATORS для параметра flags . |
7.1.0 | При кодировании чисел с плавающей точкой ( float ) используется serialize_precision вместо precision. |
Примеры
Пример #1 Пример использования json_encode()
$arr = array( ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 , ‘d’ => 4 , ‘e’ => 5 );
?php
Результат выполнения данного примера:
Пример #2 Пример использования json_encode() с опциями
echo «Обычно: » , json_encode ( $a ), «\n» ;
echo «Теги: » , json_encode ( $a , JSON_HEX_TAG ), «\n» ;
echo «Апострофы: » , json_encode ( $a , JSON_HEX_APOS ), «\n» ;
echo «Кавычки: » , json_encode ( $a , JSON_HEX_QUOT ), «\n» ;
echo «Амперсанды: » , json_encode ( $a , JSON_HEX_AMP ), «\n» ;
echo «Юникод: » , json_encode ( $a , JSON_UNESCAPED_UNICODE ), «\n» ;
echo «Все: » , json_encode ( $a , JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE ), «\n\n» ;
echo «Отображение пустого массива как массива: » , json_encode ( $b ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $b , JSON_FORCE_OBJECT ), «\n\n» ;
echo «Отображение неассоциативного массива как массива: » , json_encode ( $c ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $c , JSON_FORCE_OBJECT ), «\n\n» ;
$d = array( ‘foo’ => ‘bar’ , ‘baz’ => ‘long’ );
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d ), «\n» ;
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d , JSON_FORCE_OBJECT ), «\n\n» ;
?>
Результат выполнения данного примера:
Обычно: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Теги: [«\u003Cfoo\u003E»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Апострофы: [«»,»\u0027bar\u0027″,»\»baz\»»,»&blong&»,»\u00e9″] Кавычки: [«»,»‘bar'»,»\u0022baz\u0022″,»&blong&»,»\u00e9″] Амперсанды: [«»,»‘bar'»,»\»baz\»»,»\u0026blong\u0026″,»\u00e9″] Юникод: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»é»] Все: [«\u003Cfoo\u003E»,»\u0027bar\u0027″,»\u0022baz\u0022″,»\u0026blong\u0026″,»é»] Отображение пустого массива как массива: [] Отображение неассоциативного массива как объекта: <> Отображение неассоциативного массива как массива: [[1,2,3]] Отображение неассоциативного массива как объекта: > Ассоциативный массив всегда отображается как объект: Ассоциативный массив всегда отображается как объект:
Пример #3 Пример использования опции JSON_NUMERIC_CHECK
echo «Строки, содержащие числа преобразуются в числа» . PHP_EOL ;
$numbers = array( ‘+123123’ , ‘-123123’ , ‘1.2e3’ , ‘0.00001’ );
var_dump (
$numbers ,
json_encode ( $numbers , JSON_NUMERIC_CHECK )
);
echo «Строки, содержащие некорректно заданные числа» . PHP_EOL ;
$strings = array( ‘+a33123456789’ , ‘a123’ );
var_dump (
$strings ,
json_encode ( $strings , JSON_NUMERIC_CHECK )
);
?>?php
Результатом выполнения данного примера будет что-то подобное:
Строки, содержащие числа преобразуются в числа array(4) < [0]=>string(7) "+123123" [1]=> string(7) "-123123" [2]=> string(5) "1.2e3" [3]=> string(7) "0.00001" > string(28) "[123123,-123123,1200,1.0e-5]" Строки, содержащие некорректно заданные числа array(2) < [0]=>string(13) "+a33123456789" [1]=> string(4) "a123" > string(24) "["+a33123456789","a123"]"
Пример #4 Пример с последовательными индексами, начинающимися с нуля, и непоследовательными индексами массивов
echo «Последовательный массив» . PHP_EOL ;
$sequential = array( «foo» , «bar» , «baz» , «blong» );
var_dump (
$sequential ,
json_encode ( $sequential )
);
?php
echo PHP_EOL . «Непоследовательный массив» . PHP_EOL ;
$nonsequential = array( 1 => «foo» , 2 => «bar» , 3 => «baz» , 4 => «blong» );
var_dump (
$nonsequential ,
json_encode ( $nonsequential )
);
echo PHP_EOL . «Последовательный массив с одним удалённым индексом» . PHP_EOL ;
unset( $sequential [ 1 ]);
var_dump (
$sequential ,
json_encode ( $sequential )
);
?>
Результат выполнения данного примера:
Последовательный массив array(4) < [0]=>string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(27) "["foo","bar","baz","blong"]" Непоследовательный массив array(4) < [1]=>string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=> string(5) "blong" > string(43) "" Последовательный массив с одним удалённым индексом array(3) < [0]=>string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(33) ""
Пример #5 Пример использования опции JSON_PRESERVE_ZERO_FRACTION
Результат выполнения данного примера: