【问题标题】:Dynamic JSON Output动态 JSON 输出
【发布时间】: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);

标签: php arrays json


【解决方案1】:

$decodedString 将作为您的 json 的对象返回。在这种情况下,它只有一个元素,即犯罪,它是另一个持有犯罪对象的对象。这些犯罪对象中的每一个都包含您要查找的数据。

foreach($decodedString as $key => $value){
    //At this step $key is the string "crimes" and the value is the object of objects inside
    foreach($value as $number => $crime){
        //Now $crime is an object of values for each crime
        echo "Level: ".$crime->crime_name."</br>";
    }
}

会输出:
炸弹威胁
计划抢劫

如果您知道犯罪是那里唯一的对象,您可能会跳过第一个 foreach。 print_r() 是你调试的好朋友。

foreach($decodedString->crimes as $number => $crime){
    //$crime is the object with the data you're looking for. 
    echo "Level: ".$crime->crime_name."</br>";
}

【讨论】:

  • 使用您的代码,我收到此错误:致命错误:无法在第 19 行的 /var/www/html/torn/Scripts/Faction/crimes.php 中使用 stdClass 类型的对象作为数组 请参阅OP 底部查看使用的代码。
  • 对不起,我应该知道 json_decode 会将其转换为对象而不是数组。改用 $value->crime_name。如果你对 $value 执行 print_r(),它会让你更好地了解你正在使用什么。我会修复上面的解决方案。您最终还需要另一个 for 循环。
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多