I will use this JSON as a model:
{
"title": "Person",
"type": "object",
"properties": {
"firstName": "Pedro",
"lastName": "Sánchez",
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
The ways to access a JSON are many (element by element, by array of elements, within a loop ...), everything depends on the structure of the same and the use you want to give the data.
You can access the elements by level.
Example:
-
Access the firstName element within properties:
$json->properties->firstName;
-
When the element you access is an array as is the case of required, in the example, you access the index:
$json->required[0]
If the sub-array has many values, you can also read them with an iterator, with a for loop or with a while.
Here are some examples:
DEMO
<?php
$string_json='{
"title": "Person",
"type": "object",
"properties": {
"firstName": "Pedro",
"lastName": "Sánchez",
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}';
//Crar objeto json
$json=json_decode($string_json);
echo "Acceder por nombres de clave:\n";
echo "Valor de la clave title: ". $json->title;
echo "\nValor de la clave firstName (dentro de properties): ". $json->properties->firstName;
echo "\n\nAlgunas claves pueden tener arrays dentro";
echo "\nValores de required (Array): 1er elemento: ". $json->required[0]. " 2º elemento: ".$json->required[1];
//Iterando
echo "\nAcceder por iterator:\n";
iterator (json_decode($string_json,true));
echo "\nSi no se conoce el contenido y la estructura se puede usar print_r:\n";
print_r ($json);
function iterator ($json)
{
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($json),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
}
RESULT
Acceder por nombres de clave:
Valor de la clave title: Person
Valor de la propiedad firstName: Pedro
Algunas claves pueden tener arrays dentro
Valores de required (Array): 1er elemento: firstName 2º elemento: lastName
Acceder por iterator:
title => Person
type => object
properties:
firstName => Pedro
lastName => Sánchez
age:
description => Age in years
type => integer
minimum => 0
required:
0 => firstName
1 => lastName
Si no se conoce el contenido y la estructura se puede usar print_r:
stdClass Object
(
[title] => Person
[type] => object
[properties] => stdClass Object
(
[firstName] => Pedro
[lastName] => Sánchez
[age] => stdClass Object
(
[description] => Age in years
[type] => integer
[minimum] => 0
)
)
[required] => Array
(
[0] => firstName
[1] => lastName
)
)