PHP increment values in JSON file

A

Anonymous

Guest
My code so far:
Code:
<?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:
[
        {
            "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:
var_dump($data)
I get output
Code:
NULL

Where do I go wrong ?

Thank you.
 
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:
[{"src":"this","counter":0},{"src":"that","counter":0}]

PHP
Code:
<?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.
 
Back
Top