对于我目前正在开发的一个工具,它输出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>"; }
我在第19行的/var/www/html/torn/Scripts/ stdClass /crimes.php中收到错误消息Fatal error: Cannot use type of object as array in /var/www/html/torn/Scripts/Faction/crimes.php
发布于 2016-01-29 04:25:15
$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>";
}https://stackoverflow.com/questions/35070842
复制相似问题