PHP simplify json array by removing empty keys


101 观看


389 作者的声誉

I need to get data from an array, but the output always varies so sometimes it has more empty keys etc.

    $id = "1";
    $url = file_get_contents("{$id}");
    $json = json_decode($url, true);

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

The problem is that to print values from it have to always put the number of empty keys first like echo $data[0][0]["test"];

How can I make it possible to only write echo $data["test"]; under any circumstance no matter how many empty keys there are?

EDIT: The json array

            "test: "testing"
作者: P. Nick 的来源 发布者: 2017 年 12 月 27 日

回应 (3)


1 作者的声誉

Just use json_decode one more time before for each . example: $json = json_decode(json_decode($url));

作者: neerajdreamer 发布者: 27.12.2017 05:46


9091 作者的声誉

 function printValue($array)
    foreach($array as $value){
       echo $value;

Basically a recursive function, if the value is an array dig down it else print the value.

This will work for all depths, be it on 2nd level or on 4th level.

作者: Danyal Sandeelo 发布者: 27.12.2017 05:46


400 作者的声誉

You could create a recursive function in order to search for a key and return it:

$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);
作者: Cornezuelo del Centeno 发布者: 27.12.2017 06:03