PHP increment values in JSON file

Links for php scripts

Moderators: gesf, Michalio

Post Reply
kyrgios

My code so far:

Code: Select all

<?PHP
header('Access-Control-Allow-Origin: *');

$src = $_POST["src"];

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

foreach ($data as $key => $entry) {
    if ($entry['src'] == $src) {
        $data[$key]['counter']++;
    }
}

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
?>



My json file looks like this:

Code: Select all

[
        {
            "src": "",
            "counter": "0"
        },
        {
            "src": "",
            "counter": "0"
        } // and so on...
Expected behaviour is to increment the counter value of matching source supplied by POST by 1.

The error in logs is PHP Warning: Invalid argument supplied for foreach() in /file.php on line 9 .

When I do

Code: Select all

var_dump($data)
I get output

Code: Select all

NULL
Where do I go wrong ?

Thank you.
AdoptiveSolution

Looks like you want the impossible.

If src in the JSON file is empty, then $_POST["src"] must be empty too in order to increase the value.

If $_POST["src"] has a value, the nothing is increased, since src is empty.

Here's my solution:

jsonFile.json

Code: Select all

[{"src":"this","counter":0},{"src":"that","counter":0}]
PHP

Code: Select all

<?php
$src = 'this'; // instead of $_POST["src"]
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );
echo '<pre>' . print_r( $data, true ) . '</pre>';
foreach ( $data as $key => $entry )
{
	if ( $entry['src'] == $src )
	{
		$data[$key]['counter']++;
	}
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );

// added to see the new values
$NewJSONString = json_decode( file_get_contents('jsonFile.json') );
echo '<pre>' . print_r( $NewJSONString, true ) . '</pre>';
?>
Reload the page to see the new values in the JSON file.
Post Reply