Michael HEYRAUD
Michael HEYRAUD

Reputation: 57

PHP if there is DATA replace else write data

I may be missing something in my PHP code. I'd like if the data.json file doesn't contain any array with the posted ID then create if is it's there then change the point to +1. Sorry if my not very clear my english is not the best. Here is my code thanks for helping.

    <?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

$date               = date("c");
$id                 = $_POST['id'];
$file               = 'data.json';

$nom                = $_POST['nom'];
$description        = $_POST['description'];
$adresse            = $_POST['adresse'];
$telephone          = $_POST['telephone'];
$img                = $_POST['img'];
$points             = $_POST['points'];

$data1 = array(
 "date"          => $date,
 "ID"            => $id,
 "nom"           => $nom,
 "description"   => $description,
 "adresse"       => $adresse,
 "telephone"     => $telephone,
 "img"           => img,
 "points"        => "1",
);

$replace=array( /* Replace these keys with these values */
    'date'          =>  $date,
    'points'        =>  ++$points,
);


$keys=array_keys( $replace );

$strjson= file_get_contents($file);

$json=json_decode( $strjson );


for ($i = 0; $i < count($json); $i++) {

  // if we found it,
  if ($json[$i]->id != $id) {
      array_push($json, $data1);
$jsonData = json_encode($json);
file_put_contents($file, $jsonData);

        } else {
foreach( $replace as $key => $value ){
            $obj->$key=$value;
        }
$json = array_values($json);
$fp = fopen($file, 'w');
fwrite($fp, json_encode($json));
fclose($fp);

  }
}

?>  

Upvotes: 0

Views: 52

Answers (1)

funilrys
funilrys

Reputation: 815

Typo

"img"           => img

Should be

"img"           => $img

Back to your case

Please consider the following as not tested unless this became an accepted answer or OP leave a comment to this answer. If you find any issue(s) feel free to edit and or leave a comment. :)

Converting JSON into array

I think the best way to achieve what you mean is to first get an array from the decoded JSON file. So we achieve that with

 $json = json_decode($strjson, true);

Indeed according to the documentation, for the second argument.

When TRUE, returned objects will be converted into associative arrays.

Check if array has the searched key

As you search the ID and we now have a JSON into an associative array format, we only have to search if the array has a given key. We achieve that with

// As you want to push ID if not found, I consider that I should search for ID
array_key_exists('ID', $json)

According to the documentation the first argument is the key that we search and the second argument the array where we have to search.

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Replacement/Update of the date and points

Besides the fact that I don't understand your use of $obj->$key=$value; as $obj is nowhere, I think that in your original file, you made things a bit complicated ...

Now that we have $json in an array format, the easiest way to achieve the replacement/update is to read the key and value from $replace with a loop and replace the data from with the file which have the same key with the value according to $replace[$key]

In another word, it'll be better to do the following

// If we find the ID and the ID is different from the current $id, we update
// some values
foreach ($replace as $key => $value) {
    // We get the $replace[$key] and update $json[$key] with the value of $replace[$key]
    $json[$key] = $value;
}

than

foreach( $replace as $key => $value ){
    $obj->$key=$value;
}

Final file

According to the previously explained needed changes, here's the final file

<?php

// We set the header
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: X-Requested-With');

// We assign into a variable the file name
$file = 'data.json';

// We assign/get the data we gonna save into the file
$date = date('c');
$id = $_POST['id'];
$nom = $_POST['nom'];
$description = $_POST['description'];
$adresse = $_POST['adresse'];
$telephone = $_POST['telephone'];
$img = $_POST['img'];
$points = $_POST['points'];

// We create an array with the needed information to encode into JSON format
$data1 = array(
    'date' => $date,
    'ID' => $id,
    'nom' => $nom,
    'description' => $description,
    'adresse' => $adresse,
    'telephone' => $telephone,
    'img' => $img,
    'points' => '1',
);

// We manage here the data that need to be updated in case we do not match 'ID '
// or 'ID' from JSON file is different from the current $id
$replace = array(
    'date' => $date,
    'points' => ++$points,
);

// We get the content of the JSON file
$strjson = file_get_contents($file);

// We decode it into an associative array
$json = json_decode($strjson, true);

// We preset the data (in certain way to apply DRY... More info there : https://en.wikipedia.org/wiki/Don%27t_repeat_yourself))
$jsonData = json_encode(array());

if (array_key_exists('ID', $json) && $json['ID'] != $id) {
    // If we find the ID and the ID is different from the current $id, we update
    // some values
    foreach ($replace as $key => $value) {
        // We get the $replace[$key] and update $json[$key] with the value of $replace[$key]
        $json[$key] = $value;
    }

    // We encode into JSON format
    $jsonData = json_encode($json);
} else {
    // We save the new data into the file
    // I do prefer:
    // $json = array_merge($json, $data1);
    // but the following should work (not tested)
    // Also, there's no need to push ...
    // array_push($json, $data1); // ==> Commented because this is not needed if I understood correctly what you're trying to do
    $jsonData = json_encode($data1);
}

// To apply DRY
// We save the data into the file
file_put_contents($file, $jsonData);
?>

Why did I commented out array_push($json, $data1);?

I commented it out because, in my perception, we push the content of $data1 into the file so no need to use a $json variable ...

Upvotes: 1

Related Questions