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.