在Cron控制器中,我编写了以下函数:-
public function football() {
$jsonData = file_get_contents('http://localhost/football/football/api/football_api.php');
}
$jsonData is returning the following object:-
stdClass Object
(
[callum-paterson] => stdClass Object
(
[id] => 1
[unique_id] => callum-paterson
[name] => Callum Paterson
[club] => Cardiff City
[position] => Defender
[national_team_name] => Unknown
[birthdate] => 1994-10-13
[birthplace] => Unknown
[nationality] => Unknown
[preferred_foot] => Unknown
[weight] => 76
[height] => 183
[shirt_number] => 13
[real_position] => Full Back
[real_position_side] => Right
[country] => Scotland
[photo_url] => https://img.footballindex.co.uk/callum-paterson-g-t1.jpg
)
[chicharito] => stdClass Object
(
[id] => 3
[unique_id] => chicharito
[name] => Chicharito
[club] => West Ham United
[position] => Forward
[national_team_name] => Unknown
[birthdate] => 1988-06-01
[birthplace] => Guadalajara
[nationality] => Mexico
[preferred_foot] => Right
[weight] => 73
[height] => 175
[shirt_number] => 17
[real_position] => Striker
[real_position_side] => Centre
[country] => Mexico
[photo_url] => https://img.footballindex.co.uk/javier-hernandez-g-t6.jpg
)
$ jsonData返回1064条记录。这里我展示了一些。所以我想在stdclass-object_index(例如[callum-paterson])中打印所有记录(例如id,unique_id,名称等)。
我是JSON的新手。所以我做不到。任何帮助将不胜感激。我尝试过foreach,但无法正常工作。
答案 0 :(得分:0)
避免使用作为数据类型的变量名。它们包含的内容更有用。当变量尚未使用时,$data
是可以接受的。
public function football() {
$footballers = file_get_contents('http://localhost/football/football/api/football_api.php');
foreach ($footballers as $footballer => $data) {
$footballers[$footballer] = json_decode($data);
}
return $footballers;
}
答案 1 :(得分:0)
我解决了自己的问题,这是我的解决方案:-
public function football() {
header('Content-Type: application/json');
$tmp = array();
$footballers = json_decode(file_get_contents('http://localhost/football/football/api/football_api.php'));
foreach ($footballers as $footballer => $data) {
$tmp[] = $data->unique_id;
}
print_r($tmp);
}
$ tmp保存所有unique_id。这样,您可以打印所有值。