Массив декодирования Php json

#php #arrays #json

#php #массивы #json

Вопрос:

у меня есть строка json. Но я не могу получить доступ к значениям.

 $json_string : '{"05526":[{"name":"rapertuar","surname":"xyz","notes":[{"mat1":"59","eng2":"60"},{"mat2":"59","eng2":"60"}]}]}';
$content = file_get_contents($json_string);
$json_a = json_decode($content, true);

echo $json_a['05526']['0']['name'];
echo $json_a['05526']['0']['name']['notes']['0']['mat1'];
  

Как я могу исправить этот код? Спасибо

Комментарии:

1. file_get_contents($json_string) ? Что это?

2. Почему вы пытаетесь получить доступ к файлу, если у вас есть только строка?

Ответ №1:

 $json_string : '{"05526":[{"name":"rapertuar","surname":"xyz","notes":[{"mat1":"59","eng2":"60"},{"mat2":"59","eng2":"60"}]}]}';

// you don't need this line
//$content = file_get_contents($json_string);
$json_a = json_decode($json_string, true);

echo $json_a['05526']['0']['name'];
echo $json_a['05526']['0']['name']['notes']['0']['mat1'];
  

Ответ №2:

Нет необходимости использовать file_get_contents , если вы сохраняете JSON в строке, а затем декодируете его. Следуйте приведенному ниже подходу:

 $json_string = '{"05526":[{"name":"rapertuar","surname":"xyz","notes":[{"mat1":"59","eng2":"60"},{"mat2":"59","eng2":"60"}]}]}';
$json_a = json_decode($json_string, true);

echo $json_a['05526']['0']['name']; // rapertuar
echo $json_a['05526']['0']['notes']['0']['mat1']; // 59