2

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

7
  • Note thats invalid json, I just formated for you. Commented Nov 30, 2017 at 20:34
  • Can we please get a var_dump( $data ); without any additional mods (in your comment you say json_encode - leave that out, and use var_dump or var_export) Commented Nov 30, 2017 at 20:43
  • 'var_dump($data)' before merged line: 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" } } Commented Nov 30, 2017 at 20:44
  • after merged line: 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" } } } Commented Nov 30, 2017 at 20:45
  • Seems like you just want 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. Commented Nov 30, 2017 at 20:46

2 Answers 2

2

So - you don't really need a "key => value" pair, you just want to append the array to your main array.

The simplest way to do this, given your code, is this (NOTE: replace your entire if / else statement with this):

$new_id = count( (array)$data ) + 1;
$data[ $new_id ] = array('id' => $new_id, 'name' => $_POST['name'], 'email' => $_POST['email'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'categories' => $_POST['categories'], 'image' => $imageFilePath);
file_put_contents( 'blogPosts.json', json_encode( $data ) );
Sign up to request clarification or add additional context in comments.

2 Comments

Just noticed. If the JSON file is empty before trying to add, this looses the key. (outputting [{"id":"1","name":"lew","email":"[email protected]","title":"lew","description":"lew","categories":["sport"],"image":"no_image"}] instead of {"id":"1","name":"lew","email":"test@hotmail.‌​co.uk","title":"lew"‌​,"description":"lew"‌​,"categories":["scie‌​nce"],"image":"no_im‌​age"}}
Sorry, I incorrectly copied the second example. It was: {"1":{"id":"1","name":"lew","email":"test@hotmail.‌​co.uk","title‌​":"lew"‌​,"descripti‌​on":"lew"‌​,"categor‌​ies":["scie‌​nce"],"‌​image":"no_im‌​age"}‌​}
1

This code will work and do want you seem to want !

(This is just a solution, not a elegant or even something i would do...)

<?php
$data = file_get_contents('blogPosts.json');
$data = (empty($data)) ? null : json_decode($data, true);

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);
    $blog_entry = array("1" => $post_array);
    file_put_contents('blogPosts.json', json_encode($blog_entry));
}
else {
    $post_array = array('id' => $new_id, 'name' => $_POST['name'], 'email' => $_POST['email'], 'title' => $_POST['title'], 'description' => $_POST['description'], 'categories' => $_POST['categories'], 'image' => $imageFilePath);
    $data[] = $post_array;
    file_put_contents('blogPosts.json', json_encode($data));
}

var_dump($data);

this would work exactly the same and with less code ...

<?php
$data = file_get_contents('blogPosts.json');
$data = (empty($data)) ? array() : json_decode($data, true);

$new_id = count($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);

$data[] = $post_array;
file_put_contents('blogPosts.json', json_encode($data));

var_dump($data);

(edited, had a mistake...)

2 Comments

Thanks for taking the time to reply, this solution worked well - and was presented more elegantly by @cale_b
Just a code-style observation: data == NULL is probably better represented as simply ! data, as data == NULL is really the same as "data is falsey", due to the loose equal operator. If it is truly checking for null, it should be data === NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.