我正在制作笔记本,登录并写笔记。所有信息都必须存储到文本文件中(我知道DB更简单,但存储到文件是项目要求)。
到目前为止,我已完成登录,创建新成员,添加新笔记。我现在需要编辑这些笔记。
当我在视图中显示所有笔记(然后用户登录)时,我会向这些属于登录用户的笔记添加一个锚点,即“编辑”。
foreach ($notes as $item)
{
if ($item['user'] == $name) // if post belongs to logged in user, I add "edit"
{
echo "<h3>", $item['user'], " " ,$item['date'], "</h3>";
echo "<p>", $item['content'], " ", anchor('site/edit_note', 'Edit'), "</p>";
}
//if posts belongs to other users, notes are just posted
else {
echo "<h3>", $item['user'], " " ,$item['date'], "</h3>";
echo "<p>", $item['content'], "</p>";
}
}
我的文本文件结构:
some user : some user post : date
我想我需要传递一些这些锚点的信息,使它们成为唯一的,并知道在文件中编辑的位置,并以文本区域的形式显示该帖子。我已经阅读了关于URI类和URL帮助器的内容,但不确定我需要什么?
后来我想我会做一些文件信息数组,重写数组中需要的帖子然后将数组存储在文件中。我只是想知道这是正确的方法吗?
答案 0 :(得分:1)
我认为您应该将文件结构更改为每行/帖子都有唯一的ID:
unique id : some user : some user post : date
然后,您可以像这样设置网址:
echo "<p>", $item['content'], " ", anchor('site/edit_note/'.$item['id'], 'Edit'), "</p>";
并且您的edit_note方法需要接受ID参数
function edit_note($requested_id = null)
{
if (!$requested_id) { return ""; }
// get the requested id item from your file, that is below
// The [`file()` function][1] will return the contents of a file as an array.
// Each array item will be a line of the file. So if each of your posts are a
// line, then you can just do:
$rows = file('file/path/here');
//Filter the $rows array to view just the ID needed
$selected_row = array_filter($rows, function($row) use ($requested_id) {
$row_items = explode(' : ', $row);
return ($row_items[0] == $requested_id);
});
$row_items = explode(' : ', $selected_row);
// now you'll have the contents of the requested post in the $row_items array
// and can call a view and pass it that data
$data['row_items'] = $row_items;
$this->load->view('edit_view', $data);
}