根据给定的json对象更新json数据

时间:2016-04-15 09:44:32

标签: php json

首先我想从json文件中读取'Likes'值更新它,例如加上一两个。

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

使用“ProductName”:“Apsara”将其插回json。

apsara_json_document_v2.json

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

我发布了两个字段到php,php搜索并提取包含ProductName的数组,我希望相应地更新喜欢。这是我的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结果中的like值。

1 个答案:

答案 0 :(得分:1)

好吧,您只需要使用intval将值解析为int,进行数学计算,并将其作为带strval的字符串放回:

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

要注意的一件事是要知道intval在出错时返回0。因此,在进行错误检查时必须小心:

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);

此外,命名数组$user中的键是非常混乱的。为清楚起见,请将其称为$index:)