Home > Mobile >  PHP add key data to json
PHP add key data to json

Time:04-08

Have a nice day. I have created the following basics:

{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        }
    }
}

I need to add the following lines to the same key:

{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        },
        "h265": {
            "url": "TEST",
            "expire": 1649456380
        }
    }
}

But whatever I try, it does this to me:

{
    "1111": {
        "h264": {
            "url": "TEST",
            "expire": 1649453177
        },
        "0": {
            "h265": {
                "url": "TEST",
                "expire": 1649456380
            }
        }
    }
}

Here is some sample code:

$time = time();
$codec = "h265";
$url = "TEST";
$id = "1111";
$data = json_decode(file_get_contents('./data.json'), true);
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents('./data.json', $data);

Can someone advise me not to add the 0 key to me there

CodePudding user response:

Change:

$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);

To:

$post_data = array($codec => array('url' => $last_line,'expire' => $time));
$data[$id]['h265'] = $post_data;
  • Related