Php convert json array to php array

Руководство по обработке JSON в PHP

JSON расшифровывается как JavaScript Object Notation. JSON — это стандартный легкий формат обмена данными, который просто и быстро анализировать и генерировать.

JSON, как и XML, представляет собой текстовый формат, который легко писать и легко читать как людям, так и для компьютерам, но в отличие от XML, структуры JSON-данных имеют меньшую пропускную способность, чем их версии XML. JSON основан на двух основных структурах:

  • Object: определяется как набор пар ключ/значение ( key:value ). Каждый объект начинается с левой фигурной скобки < и заканчивается правой фигурной скобкой >. Несколько пар ключ/значение разделяются запятой , .
  • Array: это упорядоченный список значений. Массив начинается с левой скобки [ и заканчивается правой скобкой ] . Значения разделяются запятой , .

В JSON ключи всегда являются строками, а значение может быть string , number , true или false , null и даже object или array . Строки должны быть заключены в двойные кавычки » и могут содержать escape-символы, такие как \n , \t и \ . Объект JSON может выглядеть следующим образом:

В то время как пример JSON-массива будет выглядеть примерно так:

Формат обмена данными — это текстовый формат, который используется для обмена данными между различными платформами и операционными системами. JSON — самый популярный и легкий формат обмена данными для веб-приложений.

Парсинг JSON с помощью PHP

Структуры JSON-данных очень похожи на массивы PHP. PHP имеет встроенные функции для кодирования и декодирования данных JSON. Это функции json_encode() и json_decode() соответственно. Обе функции работают только со строковыми данными в кодировке UTF-8.

Читайте также:  Python unpack list to tuple

Кодирование данных JSON в PHP

В PHP функция json_encode() используется для кодирования значения в JSON-формат. Кодируемое значение может быть любым типом данных PHP, кроме ресурса, такого как база данных или дескриптор файла. В приведенном ниже примере показано, как кодировать ассоциативный массив PHP в объект JSON:

65, "Harry"=>80, "John"=>78, "Clark"=>90); echo json_encode($marks); /* Выводит: */ ?>

Точно так же вы можете закодировать индексированный массив PHP в массив JSON, например:

Вы также можете заставить функцию json_encode() возвращать индексированный массив PHP как объект JSON, используя параметр JSON_FORCE_OBJECT , как показано в примере ниже:

Как вы можете видеть в приведенных выше примерах, неассоциативный массив может быть закодирован как массив или объект. Однако ассоциативный массив всегда кодируется как объект.

Декодирование данных JSON в PHP

Расшифровать или декодировать JSON-данные так же просто, как и закодировать. Вы можете использовать PHP-функцию json_decode() для преобразования закодированной JSON-строки в соответствующий тип данных PHP. В следующем примере показано, как декодировать или преобразовать объект JSON в объект PHP.

'; var_dump(json_decode($json)); /* Выводит: object(stdClass)#1 (4) < ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) >*/ ?>

По умолчанию функция json_decode() возвращает объект. Однако вы можете дополнительно указать второй параметр $assoc , который принимает логическое значение, которое при установке в качестве true для JSON-объекта декодируется в ассоциативные массивы. По умолчанию — false . Вот пример:

'; var_dump(json_decode($json, true)); /* Выводит: array(4) < ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) >*/ ?>

Теперь давайте рассмотрим пример, который покажет вам, как декодировать JSON-данные и получить доступ к отдельным элементам объекта или массива JSON в PHP.

'; // Декодируем JSON-данные в ассоциативный массив PHP $arr = json_decode($json, true); // Доступ к значениям из ассоциативного массива echo $arr["Peter"]; // Выводит: 65 echo $arr["Harry"]; // Выводит: 80 echo $arr["John"]; // Выводит: 78 echo $arr["Clark"]; // Выводит: 90 // Декодируем JSON-данные в объект PHP $obj = json_decode($json); // Доступ к значениям из объекта echo $obj->Peter; // Выводит: 65 echo $obj->Harry; // Выводит: 80 echo $obj->John; // Выводит: 78 echo $obj->Clark; // Выводит: 90 ?>

Вы также можете просмотреть декодированные данные с помощью цикла foreach() , например:

'; // Декодируем JSON-данные в ассоциативный массив PHP $arr = json_decode($json, true); // Цикл ассоциативного массива foreach($arr as $key=>$value)< echo $key . "=>" . $value . "
"; > echo "
"; // Декодируем JSON-данные в объект PHP $obj = json_decode($json); // Цикл объекта foreach($obj as $key=>$value)< echo $key . "=>" . $value . "
"; > ?>

Извлечение значений из вложенных JSON-данных в PHP

Объекты и массивы JSON также могут быть вложенными. Объект JSON может произвольно содержать другие объекты JSON, массивы, вложенные массивы, массивы объектов JSON и т. д. В следующем примере показано, как декодировать вложенный объект JSON и распечатать все его значения в PHP.

 /* Запускаем основной цикл Если значение само по себе является массивом, рекурсивно вызываем эту же функцию Добавляем все найденные значения в массив элементов вывода и увеличиваем счетчик на 1 для каждого найденного значения */ foreach($arr as $key=>$value) < if(is_array($value))< printValues($value); >else < $values[] = $value; $count++; >> // Возвращаем общее количество и значения, найденные в массиве return array('total' => $count, 'values' => $values); > // Назначаем закодированную JSON-строку переменной PHP $json = ' < "book": < "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": < "paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11" >> >'; // Декодируем JSON-данные в формат ассоциативного массива PHP $arr = json_decode($json, true); // Вызываем функцию и печатаем все значения $result = printValues($arr); echo "

" . $result["total"] . " value(s) found:

"; echo implode("
", $result["values"]); echo "
"; // Выводим одно значение echo $arr["book"]["author"] . "
"; // Выводит: J. K. Rowling echo $arr["book"]["characters"][0] . "
"; // Выводит: Harry Potter echo $arr["book"]["price"]["hardcover"]; // Выводит: $20.32 ?>

kwork banner 480x320 skillbox banner 480x320 beget banner 480x320

Насколько публикация полезна?

Нажмите на звезду, чтобы оценить!

Источник

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’
)
)
)
);

// 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:

Источник

Оцените статью