【发布时间】: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