Ajax -the Max Ajax -the Max - 2 years ago 81
PHP Question

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".


"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..


//checking if the script received a post request or not
//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';
//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);
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);
echo "error";

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

Answer Source

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']);
$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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download