2

How can I add new data to a JSON structure?

Here is the JSON in json.txt:

[
 {"name":"foo","number":"1"},
 {"name":"bar","number":"2"},
 {"name":"Hello","number":"3"}
]

Now I want to add a new line {"name":"good day","number":"**"}

$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newdata = array('name'=>'good day', 'number' => '**');// how to add `number` automatic `+1`, make it to `4` with php code?
$data[] = $newdata;
file_put_contents($file, json_encode($data));
5
  • your code looks ok, what do you get as output? Commented Jul 19, 2011 at 18:45
  • 4 because it will be the fourth entry in the array, or because it's the max number (3) + 1? Commented Jul 19, 2011 at 18:45
  • @Yoshi, if I add more datas in this txt, and how to insert the number automaticlly increase? Commented Jul 19, 2011 at 18:47
  • "Data" is already the plural of "datum". Commented Jul 19, 2011 at 18:48
  • 2
    It looks to me like this number property should not exist. The subobjects already have a natural ordering, so remove the redundant and hard-to-maintain number field and lose nothing. Commented Jul 19, 2011 at 18:49

2 Answers 2

2
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newNumber = max(array_map(
   function($e) {return intval($e['number']);},
$data)) + 1;
$newdata = array('name'=>'good day', 'number' => strval($newNumber));
$data[] = $newdata;
file_put_contents($file, json_encode($data));

In php < 5.3, replace the $newNumber = statement with:

$newNumber = max(array_map(
    create_function('$e', 'return intval($e["number"]);'),
$data)) + 1;
Sign up to request clarification or add additional context in comments.

2 Comments

Parse error: syntax error, unexpected T_FUNCTION, expecting ') on line 4
@fish man I'm assuming you're testing with an old php version. Updated the answer with code that should work for php<5.3 too.
1

In your example, the number is continuous. Why not use end make the number auto increase?

<?php
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$number = (end($data)->number) + 1;
$newdata = array('name'=>'good day', 'number' => ''.$number.''); // how to add `number` automatic `+1`, make it to `4` with php code?
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>

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.