【问题标题】:PHP won't update JSON filePHP 不会更新 JSON 文件
【发布时间】:2014-07-21 09:28:12
【问题描述】:

这是我的 JSON 文件目前的样子:

{"coins":"0","uses":"0"}    

我正在尝试使用以下 PHP 更新它的值:

$jsonString = file_get_contents('/path/money_maker.json');
$data = json_decode($jsonString);
$data["coins"] = $data["coins"] + $coins;
$data["uses"] = $data["uses"] + 1;
$newJsonString = json_encode($data);
file_put_contents('/path/money_maker.json', $newJsonString);

但是,它不起作用。怎么会?我试过做一些研究,但到目前为止没有任何帮助。

【问题讨论】:

  • “不工作”是一个非常糟糕的问题描述,所以我只能猜测 - 如果你想将它用作数组,它可能应该是 json_decode($jsonString, true);。如果不传递第二个参数,则会返回一个对象,因此您必须使用 $data->coins; 访问属性。
  • json_decode 返回一个对象,但您将其视为数组。如果需要数组,请使用 json_decode(.., true)。

标签: php file-get-contents json


【解决方案1】:

文件的内容是json对象。你不能像array一样使用它。试试这个

$jsonString = file_get_contents('money-maker.json');
$data = json_decode($jsonString);
$data->coins = $data->coins + $coins;
$data->uses = $data->uses + 1;
$newJsonString = json_encode($data);
file_put_contents('money-maker.json', $newJsonString);

或者你可以先转换再使用。

【讨论】:

    【解决方案2】:

    sgt 的回答是正确的,但您也可以使用 assoc 参数让 json_decode 创建数组而不是 PHP 手册 (http://be2.php.net/manual/en/function.json-decode.php) 中看到的对象:$data = json_decode($jsonString, true);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-05
      • 2012-07-07
      • 2020-04-08
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2019-04-08
      • 2017-07-31
      相关资源
      最近更新 更多