I am having trouble trying to add a new key-value pair to an existing JSON object. I have tried using array_merge, array_push, array_replace... all without success.
Desired format (blog entry case study)
{
"1":{
"id":"1",
"name":"lew",
"email":"[email protected]",
"title":"lew",
"description":"lew",
"categories":[
"science"
],
"image":"no_image"
},
"2":{
"2",
"name":"lew",
"email":"[email protected]",
"title":"lew",
"description":"lew",
"categories":[
"science"
],
"image":"no_image"
}
}
Here is my current code (not that if the JSON file is empty, I will simply add the first element, without the need of a merge etc.)
if ($data == null) {
$post_array = array('id' => "1",'name' => $_POST['name'], 'email' => $_POST['email'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'categories' => $_POST['categories'], 'image' => $imageFilePath);
echo json_encode($post_array) . "<br>";
$blog_entry = array("1" => $post_array);
echo json_encode($blog_entry) . "<br>";
file_put_contents('blogPosts.json', json_encode($blog_entry));
} else {
$length_of_data = count($data);
$new_id = (string)($length_of_data + 1);
$post_array = array('id' => $new_id, 'name' => $_POST['name'], 'email' => $_POST['email'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'categories' => $_POST['categories'], 'image' => $imageFilePath);
$merged = array_push($data, array($new_id => $post_array));
file_put_contents('blogPosts.json', json_encode($merged));
}
Any suggestions are welcomed, thank you
var_dump( $data );without any additional mods (in your comment you say json_encode - leave that out, and usevar_dumporvar_export)array(1) { [1]=> array(7) { ["id"]=> string(1) "1" ["name"]=> string(3) "lew" ["email"]=> string(28) "[email protected]" ["title"]=> string(3) "lew" ["description"]=> string(3) "lew" ["categories"]=> array(1) { [0]=> string(7) "science" } ["image"]=> string(8) "no_image" } }array(2) { [1]=> array(7) { ["id"]=> string(1) "1" ["name"]=> string(3) "lew" ["email"]=> string(28) "[email protected]" ["title"]=> string(3) "lew" ["description"]=> string(3) "lew" ["categories"]=> array(1) { [0]=> string(7) "science" } ["image"]=> string(8) "no_image" } [2]=> array(1) { [2]=> array(7) { ["id"]=> string(1) "2" ["name"]=> string(4) "test" ["email"]=> string(15) "[email protected]" ["title"]=> string(4) "test" ["description"]=> string(5) "tedst" ["categories"]=> array(1) { [0]=> string(6) "health" } ["image"]=> string(8) "no_image" } } }array_push($data, $post_array);. The id will be assigned automatically. I'm surprised you had no success with array merge, but I can't tell what went wrong there.