2017-12-27 1541 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

为什么是负面的? –