2016-08-21 81 views
1

我传递三个参数来更新存储在json文件中的记录。 记录是根据用户的意愿动态创建和保存的。 以下代码成功找到json文件中的id,但未能更新记录。 请帮我完成更新任务!PHP:如何更新json字段

//<$_GET sid desired ID, gid name of the json file to search in, and $nam array of new values> 

$jsonitem = file_get_contents("folder1/".$gid.".txt"); 
$objitems= jsonp_decode($jsonitem,true); 
foreach ($objitems as $row) { 
    if ($row['id']==$sid) { 
     $i=0; 
     foreach ($row as $field => $value){ 
      $field->value = $nam[$i]; //this statement does not save the new values in the array!! 
      $i++; 
     } 
    } 
} 
$jsondata = json_encode($objitems,JSON_PRETTY_PRINT); 
$jsondata = "jsonp(" . $jsondata . ")"; 
file_put_contents("folder1/".$gid.".txt", $jsondata); 

回答

0

的问题是你是不是在foreach循环更新$ objitems ..和您正在使用的变量在json_encode

更换$field->value = $nam[$i];用适当的$ objitems变量数组。

的代码将是这样的:

<?php 

$jsonitem = file_get_contents("folder1/".$gid.".txt"); 
$objitems= jsonp_decode($jsonitem,true); 
$c=0; 
foreach ($objitems as $row) 
{ 
    if ($row['id']==$sid) { 
     $i=0; 
     foreach ($row as $field => $value) 
     { 
      $row[$field][$value] = $nam[$i]; 
      $i++; 
     } 
     $objitems[$c] = $row; 
    } 
    $c++; 
} 
$jsondata = json_encode($objitems,JSON_PRETTY_PRINT); 
$jsondata = "jsonp(" . $jsondata . ")"; 
file_put_contents("folder1/".$gid.".txt", $jsondata); 
+0

感谢佳日先生,你可以编写代码吗? – Shubair

+0

@Shubair我编辑了答案,添加一些代码供您参考..检查它。 –

+0

不工作) - : – Shubair