php非法字符串偏移量中遇到错误

php非法字符串偏移量中遇到错误,php,arrays,json,Php,Arrays,Json,我正在编写一个php代码,从伪json api服务器获取数据。但是我面临这个错误 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: Undef

我正在编写一个php代码,从伪json api服务器获取数据。但是我面临这个错误

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 />";

}

?>

如何删除此类错误?

正如您在中所看到的,实际数据包含在
数据
字段中

因此,请替换:

$user_data = json_decode($json_data, true);
与:


这意味着
$user\u data
包含字符串,而不是对象。我该怎么办?不客气。请考虑通过单击✔ 左边的符号。
$result = json_decode($json_data, true);
$user_data = $result['data'];