I have been working on a json decode issue (which I have already had assistance with thanks very much – PHP json_decode brings back null ).
but I find I have another problem getting the assoc array brought back by the json decode to work properly. Am I doing something wrong or is it the array?? Here is my code
<?php
$jsonurl='http://www.foxsports.com.au/internal-syndication/json/livescoreboard';
$json = file_get_contents($jsonurl,0,null,null);
$json = str_replace("jQuery.fs['scoreboard'].data =","",$json); /*
replace starting comment*/
$json =strip_tags($json); /* takes out html tags & comments*/
$json_output = json_decode($json,true);
switch(json_last_error()) {
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_NONE:
// echo ' - No errors';
break; }
function crttbl($test){ echo "</br></br>";
echo "<table border='1'>";
foreach($test as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>". $key2.": " .$row2 . "</td>";
}
echo "</tr>";
} echo "</table>";
echo "</br></br>"; }
//print_r (array_keys($json_output)); $test=$json_output["response"];
print_r(array_keys($test)); crttbl($test);
echo var_dump($test);
$test=$test['container-1']; print_r(array_keys($test)); crttbl($test);
echo var_dump($test);
$test=$test['group-content-1']; print_r(array_keys($test));
crttbl($test);
If this is the output you are after
http://cl.ly/0t2a2y3r2k2Q0B2x1o2h
Then try this:
The problem with your original code is that your object is nested more than two levels, so when you do
foreach($row as $key2=>$row2) {, $row2 is actually an Array and you simply get the wordArrayin your output.Since you can’t be 100% sure (at least I don’t think you can) of the number of levels deep the response might be, you are best off using a recursive-ish function like I provided.