For a tool I am currently making, it outputs JSON and I decode it using PHP and then echo it via the same script. In said JSON, some arrays are static and some change, such as a job id.
For example, for a request, you may get an array such as
{ "rank": "Supreme Damage Dealer", "player_id": Name, "name": "Name",
in which case, rank, player_id, and name are all static and the only thing that changes is the output.
In some arrays, such as
{ "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, },
The numbers such as 4769740 and 4769739 changes, and therefore I cannot output it as I would name/rank, because unlike name/rank the title changes.
I need to output it onto a page the same why I would the name and rank. Currently, the name and rank for example are outputted like so:
$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>";
however I cannot do the same for the crimes. How would I output the crime data?
Using code, $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>"; }
I get the error message Fatal error: Cannot use object of type stdClass as array in /var/www/html/torn/Scripts/Faction/crimes.php on line 19
$decodedString would return as an object for your json. In this case it would only have one element, crimes which is another object that holds crime objects. Each one of those crime objects contains the data you're looking for.
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>";
}
}
Would output:
Bomb threat
Planned robbery
You could potentially skip the first foreach if you know crimes is the only object there. print_r() is your friend for debugging.
foreach($decodedString->crimes as $number => $crime){
//$crime is the object with the data you're looking for.
echo "Level: ".$crime->crime_name."</br>";
}