我一直在处理json解码问题(我已经得到了帮助,非常感谢-PHP json_decode会返回null)。但我发现我在让json解码返回的assoc数组正常工作时遇到了另一个问题。是我做错了什么,还是阵列出了问题??这是我的代码
<?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);
如果这是您想要的输出http://cl.ly/0t2a2y3r2k2Q0B2x1o2h
然后试试这个:
function createTable(&$node, &$output, $key = NULL, $indent = 0) {
if ($indent > 0) {
$output .= "<tr>'n";
$output .= "<td><strong>". $key."</strong></td>";
} else {
$output .= '<tr><td>Top Level</td>';
}
if (is_object($node) || is_array($node)) {
$node = (array)$node;
$output .= "</tr>'n";
$count = 0;
foreach ($node as $k=>$v) {
createTable($node[$k], $output, $k, $indent + 1);
}
} else {
$output .= "<td>".($node === TRUE ? 1 : $node === FALSE ? 0 : $node) ."</td>";
$output .= "</tr>'n";
}
}
function outputTable($object) {
echo "<table border='1'>";
$output = "";
createTable($object, $output);
echo $output;
echo "</table>";
}
outputTable($json_output);
原始代码的问题是,对象嵌套了两个以上的级别,所以当您执行foreach($row as $key2=>$row2) {
时,$row2实际上是一个数组,您只需在输出中获得单词Array
。
由于你不能100%确定(至少我不认为你能)响应的深度级别,你最好使用我提供的递归函数。