John Davidson

PHP add key data to json

0 comments
Message:


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



My Answer:
$data = '{"name": "John", "age": 30}';
$key = "id";
$value = 123;

// Convert JSON data to associative array
$array = json_decode($data, true);

// Add key-value pair to the array
$array[$key] = $value;

// Convert array back to JSON
$newData = json_encode($array);

echo $newData; // Output: {"name": "John", "age": 30, "id": 123}

Rate this post

3 of 5 based on 4049 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us