2016-04-15 83 views
0

首先,我想從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結果的喜歡值。

+1

我已經閱讀了代碼,我已經重新格式化了代碼,並且仍然不引用您正在嘗試執行的操作。除非我相當肯定你正在爲自己**生活**比它需要更難 – RiggsFolly

回答

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

+0

謝謝馬修,抱歉的混淆 –