php非法字符串偏移中的面向错误

问题描述 投票:0回答:1

[我正在编写一个从虚拟json api服务器中获取数据的php代码。但是我遇到了这个错误。

Warning: Illegal string offset 'employee_name' in C:\xampp\htdocs\jsonapi.php on line 19
name: s

Warning: Illegal string offset 'employee_age' in C:\xampp\htdocs\jsonapi.php on line 21
name: s


Notice: Undefined index: employee_name in C:\xampp\htdocs\jsonapi.php on line 19
name:

Notice: Undefined index: employee_age in C:\xampp\htdocs\jsonapi.php on line 21
name:

有我的代码。

<?php

$api_url = 'http://dummy.restapiexample.com/api/v1/employees';

// Read JSON file
$json_data = file_get_contents($api_url);

// Decode JSON data into PHP array
$user_data = json_decode($json_data,true);

// Cut long data into small & select only first 10 records
$user_data = array_slice($user_data,0,9);

// Print data if need to debug
//print_r($user_data);

// Traverse array and display user data

foreach ($user_data as $user) {
    echo "name: ".$user['employee_name'];
    echo "<br />";
    echo "name: ".$user['employee_age'];
    echo "<br /> <br />";

}

?>

我应该如何消除这种错误?

php arrays json
1个回答
0
投票

您可以在fetched JSON中看到,实际数据包含在data字段中。

因此替换:

$user_data = json_decode($json_data, true);

使用:

$result = json_decode($json_data, true);
$user_data = $result['data'];
© www.soinside.com 2019 - 2024. All rights reserved.