這里是我的https://goalserve.com/getfeed/mytoken/topscorers/1204?json=1 的url 地址
我怎樣才能獲得“球員”資料,我想在我的 PHP Wordpress 網站上使用“最佳射手站立小部件”。
{
"?xml":{
"@version":"1.0",
"@encoding":"utf-8"
},
"topscorers":{
"@sport":"soccer",
"tournament":{
"@name":"Premier League",
"@stage_id":"12041081",
"@gid":"1204",
"@is_current":"True",
"@id":"1204",
"player":[
{
"@pos":"1",
"@name":"Mohamed Salah",
"@team":"Liverpool",
"@team_id":"9249",
"@goals":"15",
"@penalty_goals":"2",
"@id":"138653"
},
{
"@pos":"2",
"@name":"Diogo Jota",
"@team":"Liverpool",
"@team_id":"9249",
"@goals":"10",
"@penalty_goals":"0",
"@id":"374031"
},
{
"@pos":"3",
"@name":"J. Vardy",
"@team":"Leicester City",
"@team_id":"9240",
"@goals":"9",
"@penalty_goals":"0",
"@id":"159732"
}
]
}
}
}
uj5u.com熱心網友回復:
回答
https://www.php.net/manual/en/function.json-decode.php
為此,您必須首先將 json 字串解碼為 php 物件。然后,您必須深入到所需的正確資料。您可以->像這樣使用運算子執行此操作:
$players = json_decode($raw_string)->{'topscorers'}->{'tournament'}->{'player'};
請注意,如果您打算重用資料,則應保存解碼后的 json 字串的結果。不要多次解碼。
有了玩家之后,您就可以迭代資料并使用它做您想做的事情。這是一個包含您的資料的最小示例,因此您可以看到它們一起作業。
例子
資料集
<?php
$raw_string = '
{
"?xml":{
"@version":"1.0",
"@encoding":"utf-8"
},
"topscorers":{
"@sport":"soccer",
"tournament":{
"@name":"Premier League",
"@stage_id":"12041081",
"@gid":"1204",
"@is_current":"True",
"@id":"1204",
"player":[
{
"@pos":"1",
"@name":"Mohamed Salah",
"@team":"Liverpool",
"@team_id":"9249",
"@goals":"15",
"@penalty_goals":"2",
"@id":"138653"
},
{
"@pos":"2",
"@name":"Diogo Jota",
"@team":"Liverpool",
"@team_id":"9249",
"@goals":"10",
"@penalty_goals":"0",
"@id":"374031"
},
{
"@pos":"3",
"@name":"J. Vardy",
"@team":"Leicester City",
"@team_id":"9240",
"@goals":"9",
"@penalty_goals":"0",
"@id":"159732"
}
]
}
}
}';
?>
加工
<?php
$php_object = json_decode($raw_string);
$players = $php_object->{'topscorers'}->{'tournament'}->{'player'};
$html = '';
$html .= '<table>';
$html .= '<tr>';
$html .= '<td>Pos</td>';
$html .= '<td>Player</td>';
$html .= '<td>Team</td>';
$html .= '<td>Goals</td>';
$html .= '</tr>';
foreach ($players as $p) {
$html .= '<tr>';
$html .= '<td>' . $p->{'@pos'} . '</td>';
$html .= '<td>' . $p->{'@name'} . '</td>';
$html .= '<td>' . $p->{'@team'} . '</td>';
$html .= '<td>' . $p->{'@goals'} . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo($html);
?>
輸出
<table><tr><td>Pos</td><td>Player</td><td>Team</td><td>Goals</td></tr><tr><td>1</td><td>Mohamed Salah</td><td>Liverpool</td><td>15</td></tr><tr><td>2</td><td>Diogo Jota</td><td>Liverpool</td><td>10</td></tr><tr><td>3</td><td>J. Vardy</td><td>Leicester City</td><td>9</td></tr></table>
| 位置 | 播放器 | 團隊 | 目標 |
|---|---|---|---|
| 1 | 穆罕默德·薩拉赫 | 利物浦 | 15 |
| 2 | 迪奧戈·若塔 | 利物浦 | 10 |
| 3 | J·瓦爾迪 | 萊斯特城 | 9 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398150.html
標籤:php json WordPress的 接口 关联数组
