首先,我想从json文件中更新它的'Likes'值,例如将它加1或2。根据给定的json对象更新json数据
[{"ProductName": "Apsara", "Likes": "1"}]
将它插回到带有“ProductName”:“Apsara”的json中。
apsara_json_document_v2.json
[
{
"ProductName": "Apsara",
"Likes": 0
},
{
"ProductName": "Laxmipati",
"Likes": 0
}]
我张贴两个字段到PHP,PHP的搜索和提取包含产品名称的数组,我想作相应的更新喜欢。这里是我的php代码..
<?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";
}
我不知道如何更新从arraysearch结果的喜欢值。
我已经阅读了代码,我已经重新格式化了代码,并且仍然不引用您正在尝试执行的操作。除非我相当肯定你正在为自己**生活**比它需要更难 – RiggsFolly