Home > Net >  Edit only one line in json file with php
Edit only one line in json file with php

Time:01-16

Hello i Have this json file called votes.json

i want to make vote system using only php and json file to store data

this is json file

{
    "main": {
       
            "choice1": "0",
            "choice2": "0",
            "choice3": "0"
       
       
    },
    "alternative": {
       
            "choice1": "0",
            "choice2": "0",
            "choice3": "0"
   
   
}
}

i want a php function so for example i edit choice1 in the main

i want to increase the counter every time someone vote for this

so ['main'][choice1] = 1 and next time some one choose the same option become ['main'][choice1] = 2 and keep the others as the same

i tried this code but didn't work as i need

$data = file_get_contents('votes.json');

$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
   
        
        $json_arr['main']['choice1'] = $value 1;


  
}
file_put_contents('results_new.json', json_encode($value));

CodePudding user response:

As stated in the comments, you don't need a loop to increment a specific value. And you have to encode your entire array.

$data = file_get_contents('votes.json');

$json_arr = json_decode($data, true);

// Just Increase Choice1 (no need a loop for this)
$json_arr['main']['choice1']  ;

// Encode All JSon Array
file_put_contents('results_new.json', json_encode($json_arr));
  • Related