2012-03-25 74 views
-2

我一直在研究json解碼問題(我已經得到了非常多的幫助 - PHP json_decode brings back null)。 但我發現我有另一個問題得到由json解碼帶來的assoc數組正常工作。我做錯了什麼或者它是數組?這裏是我的代碼JSON DECODE Assoc Array

<?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); 
+1

究竟是什麼問題? – deceze 2012-03-25 07:14:32

+3

投票結束,因爲太局部。正如副本所說:「這個問題不可能永遠幫助未來的訪問者」。將來,至少應包括對您遇到的問題的描述,並嘗試僅發佈重新創建所需的最小代碼量。 – 2012-03-25 07:19:34

+0

糟糕,你忘了說出實際的_problem_是什麼:(' – halfer 2012-03-25 09:09:03

回答

0

如果是這樣的輸出你是後 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,你只需在輸出中得到Array這個單詞。因爲你不可能100%確定(至少我不認爲你可以)響應可能的深度級數,所以最好使用像我提供的遞歸函數。

+0

sberry - 謝謝你的迴應。這就是我需要知道的。這是我第一次嘗試解碼json。遞歸問題對我來說是新的。 – Gopher 2012-03-25 09:53:39