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

2

In the snippet of code config.json , I need every time I run a PHP script, it inserts a new line below, with the sequence number and corresponding id:

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

How do I 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. Here you would enter:

"assignment": {
                "0": "292",
                "1": "280",
                "2": "233",
                "3": "308"
                "4": "999"
            }
    
asked by anonymous 09.05.2018 / 15:50

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);
    
09.05.2018 / 16:01
3

First, transform and array :

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

$assignment = json_decode($json,TRUE);

Next, by using OR array_push or even incrementing the array manually:

1st option:

array_push($assignment,$novo_valor);

2nd 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 issue, return the JSON value to the array:

$json = json_encode($assignment);
    
09.05.2018 / 16:00
1

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

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

Function reference count ()

To insert a new line, you can use:

$json['assignment'][]=$novo_valor_a_ser_adicionado;
    
09.05.2018 / 16:00