Search code examples
phparraysjsondecodeassociative

Get JSON Group Name By ID, Not Value


I have a valid JSON file like this:

{
    "default": {
        "key_value": "Default Value"
    },
    "test": {
        "key_value": "Test Value"
    }
}

I want to get the group names as a string: "default" and "test". I know that i could use something like:

{
    "general": {
        "id": "default",
        "key_value": "Default Value"
    },
    {
        "id": "test",
        "key_value": "Test Value"
    }
}

But since my JSON is valid and my functions for reading and saving the file are already working fine, i want to achieve this with the original structure.

For experimenting I got something like:

$json = file_get_contents("file.json");
$json_data = json_decode($json, true); // I guess assoc must be true?
foreach ($json_data as $item) } // My hope was that i am able to read $item, however it is an array
    echo $item["key_value"]."<br />"; // That gives me "Default Value" and "Test Value", so thats at least something
}

I guess "default" and "test" are within the first array of the json? Now i need to find a way to read them and save them as a string. A foreach couldn't be that wrong since if a group like "test2" is added, i want to read it aswell.

I am struggling with undefined and illegal offsets (since i cant use arrays as keys?).

Since I am getting the values with something like:

$json_data["default"]["key_value"]

I thought there is something like $json_data[0] which should be "default". Apparently, this is also an array right? I've already looked around in the forums already, but unfortunately no one had the same JSON structure as their problems got solved. Maybe it's just dumb to use it like this, but there must be a way to make it work right? Possibly it's just 3 lines of code aswell and i'm not getting there right now... I've tried so much already.

Maybe you guys can help me with that.


Solution

  • I think what you want is this:

    foreach($json_data as $key=>$value) {
        echo $key, "<br />\n";
    }
    

    If you want it a bit nicer you can use array_keys():

    foreach(array_keys($json_data) as $key) {
        echo $key, "<br />\n";
    }