您好我正在尝试使用单独的给定文件中的现有json数据创建更新函数:
people.json:
[{
"firstname": "Smith",
"surname": "Johnson"
}, {
"firstname": "Sabrina",
"surname": "Khalifa"
}, {
"firstname": "Joe",
"surname": "Higgins"
}]
显示功能有效,只需获取上述所有数据。
public function display() {
$data = $this->container->get('data');
$people = $data->load('people');
$this->render('people', ['people' => $people]);
}
像load这样的容器和方法在其他类中定义。我想抓住"名字"和"姓氏"和更新,我明显做了很多错事,但它不会更新:
PeopleController.php:
public function update() {
$data = $this->container->get('data');
$people = $data->load('people');
$this->save('people', ['people' => $people]);
}
的index.php:
$app->get('/', 'App\\PeopleController:display'); //get all people
$app->put('/', 'App\\PeopleController:update'); //trying to update
正在使用的HTML:
<form>
<table>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
{% for person in people %}
<tr>
<td><input type="text" name="people[][firstname]" value="{{ person.firstname }}" /></td>
<td><input type="text" name="people[][surname]" value="{{ person.surname }}" /></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="OK" />
</form>
的DataLoader:
class DataLoader {
protected $path;
public function __construct($path) {
$this->path = $path;
}
/**
* Load data from the requested file
*
* @param string $file Filename
* @return array Decoded file contents
*/
public function load($file) {
$path = $this->getPath($file);
if (file_exists($path)) {
return json_decode(file_get_contents($path), true);
}
return [];
}
/**
* Save data to the requested file
*
* @param string $file Filename
* @param array $data Contents to save to file
*/
public function save($file, array $data) {
file_put_contents(json_encode($this->getPath($file)), $data);
}
protected function getPath($file) {
return $this->path . "/$file.json";
}
}