用PHP替换JSON中的条目

时间:2017-07-30 05:33:02

标签: php json

也许这个问题已经得到解答,但我在网上找不到任何帮助。

这是我的基本JSON文件:

[{"ID":"4215","date":"2017-05-24T05:41:44","text_wall":"Petite photo de Valence prise dimanche ","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/IMG_0056.jpeg","ville_wall":"Valence "},

{"ID":"4147","date":"2017-05-18T15:15:02","text_wall":"#lyon #paris #valence Flixbus !","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/IMG_0031.jpg","ville_wall":"Clermont-Ferrand"},

{"ID":"3834","date":"2017-05-16T03:54:27","ville_wall":"Clermont-Ferrand","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/SAM_7590.jpg","text_wall":"Nouvelle station de travail Dell E4300"},]

在这里,我希望从PHP更改“date”,“text_wall”和“ville_wall”。

根据我的知识,这是我的PHP代码,它不起作用:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

$id    = $_POST['id'];
$text  = $_POST['text_wall'];
$ville = $_POST['ville_wall'];
$date  = date("c");

$jsonString = file_get_contents('text.json');
$list = json_decode($jsonString);

//Here is the problem I think
for ($i = 0; $i < count($list); $i++) {

  if ($list[$i]->ID === $id) {
$list[$i]['text_wall'] = $text;
  }
}

$list = array_values($list);

$fp = fopen($file, 'w');
fwrite($fp, json_encode($list));
fclose($fp);

?>

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情 - 将值替换为数组并迭代。

sqlcmd blah blah blah

答案 1 :(得分:0)

首先你的json无效。需要从jsonstring中删除最后,。然后尝试下面的代码。

$jsonString = '[{"ID":"4215","date":"2017-05-24T05:41:44","text_wall":"Petite photo de Valence prise dimanche ","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/IMG_0056.jpeg","ville_wall":"Valence "},

{"ID":"4147","date":"2017-05-18T15:15:02","text_wall":"#lyon #paris #valence Flixbus !","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/IMG_0031.jpg","ville_wall":"Clermont-Ferrand"},

{"ID":"3834","date":"2017-05-16T03:54:27","ville_wall":"Clermont-Ferrand","image_wall":"https:\/\/www.originsphotography.eu\/model\/wp-content\/uploads\/2017\/05\/SAM_7590.jpg","text_wall":"Nouvelle station de travail Dell E4300"}]';



$list = json_decode($jsonString);


foreach ($list as $key => $value) {
  if ($value->ID == $id) {
    $value->text_wall = $text;
  }
}
$list = array_values($list);
$fp = fopen($file, 'w');
fwrite($fp, json_encode($list));
fclose($fp);