Ajax -the Max
Ajax -the Max

Reputation: 1069

update json data according to a given json object

Firstly I want to read 'Likes' value from json file update it, for example make it plus one or two.

[{"ProductName": "Apsara", "Likes": "1"}]

Insert it back into the json with "ProductName": "Apsara".

apsara_json_document_v2.json

[
  {
    "ProductName": "Apsara",
    "Likes": 0
  },
  {
    "ProductName": "Laxmipati",
    "Likes": 0
  }]

I am posting two fields to the php, the php searches and extracts the array containing ProductName, and I wish to update likes accordingly. Here is my php code..

<?php

    //checking if the script received a post request or not 
    if($_SERVER['REQUEST_METHOD']=='POST'){
        //Getting post data 
        $productname = $_POST['ProductName'];
        $likes = $_POST['Likes'];

        //checking if the received values are blank
        if($productname == '' || $likes == ''){
            //giving a message to fill all values if the values are blank
            echo 'please fill all values';
        }else{
            //If the values are not blank Load file
            $contents = file_get_contents('apsara_json_document_v2.json');
            //Decode the JSON data into a PHP array.
            $json = json_decode($contents, true);

            if(!function_exists("array_column")) {
                function array_column($json,'ProductName') {
                    return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
                }
            }
            $user = array_search($username, array_column( $json, 'ProductName' ) );

            if( $user !== False ) 
                // Here I want to read from $user, the 'Likes' value, update it and then 
                //insert in file
                $json[$user] = array("Likes" => $likes);
            else
                echo "product not found";

            //Encode the array back into a JSON string.
            $json = json_encode($json);

            //Save the file.
            file_put_contents('apsara_json_document_v2.json', $json);
        }
    }else{
        echo "error";
    }

I have no idea how to update likes value fro the arraysearch result.

Upvotes: 0

Views: 48

Answers (1)

Matthew Herbst
Matthew Herbst

Reputation: 32003

Well, you just need to parse the value to an int with intval, do your math, and put it back as a string with strval:

$likes = intval($json[$user]['Likes']);
$likes++;
$json[$user]['Likes'] = strval($likes);

One thing to be careful about is to know that intval returns 0 on error. So, you have to be careful when doing your error checking:

if($json[$user]['Likes'] === '0') {
  $likes = 0;
} else {
  $likes = intval($json[$user]['Likes']);
  if($likes == 0) {
    // ERROR! INTVAL returned an error
  }
}

$likes++;
$json[$user]['Likes'] = strval($likes);

Also, naming the key in the array $user is super confusing. Call it $index for clarity :)

Upvotes: 1

Related Questions