简体   繁体   中英

Add Key to Value in JSON with PHP

An API I'm using formats its JSON without a KEY to the object values. It's formatted more like an array. For reference, here's a link to the API I'm attempting to use https://opensky-network.org/apidoc/rest.html . Below is an example of what that JSON looks like.

Wrong example

{
    "time": 1535758880,
    "states": [
        [
            "First",
            "A"
        ],
        [
            "Second",
            "B"
        ]       
    ]
}

The above JSON also has square brackets for each object. Which doesn't work in my situation. They need to be curly brackets instead. Below is an example of what I'm trying to achieve. Notice that the object brackets are curly and the values have a key for each of them.

Needed Example

{
    "time": 1535758880,
    "states": [
        {
            "id": "First",
            "content": "A"
        },
        {
            "id": "Second",
            "content": "B"
        }       
    ]
}

Here is the code that I'm currently writing to find a value within the JSON.

<?php
$str = '
{
    "time": 1535758880,
    "states": [
        {
            "id": "First" ,
            "content": "A"
        },
        {
            "id": "Second" ,
            "content": "B"
        }       
    ]
}';

$json = json_decode($str);
foreach($json->states as $item)
{
    if($item->id == "Second")
    {
        echo $item->content;  
    }
}
?>

My overall question is, how can I add id and content to my JSON and also replace the the square brackets for each object with curly brackets? I'm thinking that I need do a str_replace() somehow. But I'm not really sure how to approach this.

You need to recast the array, and then re-encode it back to json. Something like this:

$formatted = json_decode($str);
foreach ($formatted->states as $key => $value) {
    $tmp = array(
        'id' => $value[0],
        'content' => $value[1]
    );
    $formatted->states[$key] = $tmp;
}

// If you want this in array format you are done here, just use $formatted.

// If you want this back in json format, then json_encode it.
$str = json_encode($formatted);

Definetly don't try string replace.

First off I would question if you really need that conversion from an array to an object. $item[0] not much worse than $item->id . If you really want to you could make your code more obvious and make variables for the indexes.

$id = 0;
$content = 1;

if ($item[$id] == 'Second') {
    echo $item[$content];
}

But if for whatever reason you a stuck having to convert you can use the code in mopsyd post above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM