【发布时间】:2016-01-28 19:57:43
【问题描述】:
对于我目前正在制作的工具,它输出 JSON,我使用 PHP 对其进行解码,然后通过相同的脚本对其进行回显。在上述 JSON 中,有些数组是静态的,有些是变化的,例如作业 ID。
例如,对于一个请求,你可能会得到一个数组如
{
"rank": "Supreme Damage Dealer",
"player_id": Name,
"name": "Name",
在这种情况下,rank、player_id 和 name 都是静态的,唯一改变的是输出。
在一些数组中,比如
{
"crimes": {
"4769740": {
"crime_id": 3,
"crime_name": "Bomb threat",
"participants": "1616976,1848006,1829524",
"time_started": 1453948278,
"time_completed": 1454207478,
},
"4769739": {
"crime_id": 4,
"crime_name": "Planned robbery",
"participants": "612285,1603035,579999,1858750,1875355",
"time_started": 1453948245,
"time_completed": 1454293845,
},
4769740 和 4769739 等数字发生了变化,因此我无法像命名/排名那样输出它,因为与名称/排名不同,标题会发生变化。
我需要将它输出到一个页面上,就像我将名称和排名一样。 目前,例如名称和排名的输出如下:
$jsonurl = "http://api.torn.com/user/$id?selections=basic&key=$key";
$json = file_get_contents($jsonurl);
$decodedString = json_decode($json, true);
//var_dump($decodedString);
echo "Level: ".$decodedString["level"]."</br>";
echo "Name: ".$decodedString["name"]."</br>";
但是我不能对这些罪行做同样的事情。我将如何输出犯罪数据?
使用代码,
$jsonurl = "http://api.torn.com/faction/7709?selections=crimes&key=key";
$json = file_get_contents($jsonurl);
$decodedString = json_decode($json);
foreach($decodedString as $key => $value){
//At this step $key is 4769740
//$value is an array of the values inside
echo "Level: ".$value["crime_name"]."</br>";
}
我收到错误消息 Fatal error: Cannot use object of type stdClass as array in /var/www/html/torn/Scripts/Faction/crimes.php on line 19
【问题讨论】:
-
你试过foreach语句了吗? foreach($decodedString["crimes"] AS $key => $value) {echo $decodedString["crimes"][$key];}
-
$decodedString = json_decode($json);必须是$decodedString = json_decode($json, true);。