paddibr
paddibr

Reputation: 77

PHP read file (array) as array

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?

Upvotes: 1

Views: 74

Answers (2)

Phellipe Ribeiro
Phellipe Ribeiro

Reputation: 481

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);

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

<?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

Upvotes: 0

Related Questions