1

How can I read a json array and add/merge a new element to it?

The content of my file data.json looks like this array:

[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]

new element array example:

Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )

I used explode() and file() but it failed (delimiter for index 1..)..

has someone another idea or it is the right way to solve?

2
  • foreach first then use explode. Commented Nov 25, 2015 at 0:42
  • yes, the foreach stands.. Commented Nov 25, 2015 at 10:45

2 Answers 2

2

Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().

After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.

Then you may append a new item to that array using [] suffix eg. $a[] = $b;

These three steps are exemplified below.

// get raw json content
$json = file_get_contents('data.json');

// translate raw json to php array
$array = json_decode($json);

// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);

In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().

// translate php array to raw json
$json = json_encode($array);

// update file
file_put_contents('data.json', $json);
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors

see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode

Comments

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.