How to insert a new line in the json file, using PHP?

Asked

Viewed 1,237 times

2

In the code snippet config.json, need that whenever you run a PHP script, it will insert a new line below, with the number in sequence and corresponding id:

"assignment": {
                "0": "292",
                "1": "280",
                "2": "233",
                "3": "308"
            }

How do I make him find these numbers (1,2,3,etc) to insert the next one in sequence and put the $id variable in the second column?

Ex: the next $id = 999. Then you would insert:

"assignment": {
                "0": "292",
                "1": "280",
                "2": "233",
                "3": "308"
                "4": "999"
            }

3 answers

4


You can do it this way

// extrai a informação do ficheiro
$string = file_get_contents("config.json");
// faz o decode o json para uma variavel php que fica em array
$json = json_decode($string, true);

// aqui é onde adiciona a nova linha ao ao array assignment
$json["assignment"][] = "999";

// abre o ficheiro em modo de escrita
$fp = fopen('config.json', 'w');
// escreve no ficheiro em json
fwrite($fp, json_encode($json));
// fecha o ficheiro
fclose($fp);

3

First, transform and array:

/*Vendo que, a variável é o nome do array, previamente implementado*/

$assignment = json_decode($json,TRUE);

In sequence using OR array_push or even incrementing the array manually:

first option:

array_push($assignment,$novo_valor);

second option:

$assignment[] = $novo_valor;

Seeing that your index is in number, it is not necessary to indicate a value in the index. To resolve your question, return the JSON value to the array:

$json = json_encode($assignment);
  • i am new with this, where do I call the config.json file? the $new_value would be for example: $new_value = '999'?

  • @Leandromarzullo in Ricardo Rosa’s Reply he shows the file_get_contents, to have the contents of the file.

1

Counting the number of arrays within 'assigniment', as the function count() starts at 1, so it will always have a value greater than the last id, in your case:

$id=count($json['assignment']);

Reference of the Count function()

To insert a new line, you can use:

$json['assignment'][]=$novo_valor_a_ser_adicionado;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.