2017-12-27 1526 views
1

我需要從陣列獲取數據簡化JSON數組,但輸出總是變化,從而有時它有更多的空鍵等PHP通過除去空鍵

$id = "1"; 
    $url = file_get_contents("http://example.com/?api={$id}"); 
    $json = json_decode($url, true); 

    foreach($json as $data) 
    { 
     echo $data[0][0]["test"]; 
    } 

的問題是,從它打印值必須始終將空鍵的數量設置爲echo $data[0][0]["test"];

無論有多少空鍵,在任何情況下如何才能使echo $data["test"];成爲可能?

編輯: JSON數組

[ 
    [ 
     { 
      "test: "testing" 
     } 
    ] 
] 
+0

請告訴我們的陣列結構的一個例子。 –

+0

只寫你的功能 – splash58

+0

添加了json數組結構 –

回答

4
function printValue($array) 
    foreach($array as $value){ 
    if(is_array($value)){ 
     printValue($value) 
    } 
    else 
     echo $value; 
    } 
} 

基本上是一個遞歸函數,如果值是array向下挖掘它在其他打印值。

這將適用於所有的深度,無論是在二級還是四級。

-3

之前只需使用json_decode一次每個。例如:$ json = json_decode(json_decode($ url));

+0

這不會起作用,json_decode需要一個字符串作爲輸入,如果你在json_decode之後再次執行json_decode,那麼你會嘗試解碼一個對象或數組,並且會拋出一個錯誤。 –

-1

你可以爲了創建一個遞歸函數來搜索鍵和返回它:

$json = '[ 
    [ 
     { 
      "test" : "testing" 
     } 
    ] 
]'; 
//Cast to array the json 
$array = json_decode($json,true); 
echo searchKey("test",$array); 

function searchKey($key,$array) { 
    //If key is defined, print it 
    if (isset($array[$key])) { 
     return $array[$key]; 
    } 
    //Else, search deeper 
    else { 
     foreach ($array as $value) { 
      if (is_array($value)) { 
       return searchKey($key,$value); 
      } 
     } 
    } 
} 
+0

爲什麼是負面的? –