javascript - 如何从 json 表中删除?
问题描述
我有一个如下表:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nazwa</th>
<th scope="col">Cena</th>
<th scope="col">Kupujący</th>
<th scope="col"> </th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $value): ?>
<tr>
<td><?php echo $value['id']; ?></td>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['price']; ?></td>
<td><?php echo $value['buyer']; ?></td>
<td><button type="button" name="button2" >Usuń</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
如何通过单击表格最后一列中的按钮从该列表中删除项目?
我的PHP:
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
感谢您的帮助,我不知道如何通过单击按钮获得价值:/
解决方案
您的数据似乎是从文件中获取的,因此要完成它,您需要在同一个 php 脚本中完成所有这些步骤:
- 从此文件中获取数据
- 解析数据
json_decode
- 使用删除项目
unset($data['id'])
- 将新数据保存在同一个文件中
这是一个例子:
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
// here we go
if(isset($_POST['item_key']) && !empty($_POST['item_key'])) {
$data = array_values($data);
$i=0;
foreach($data as $element) {
//check if it's the right item
if(intval($_POST['item_key']) == $element['id']){ // intval only if you are sure id passed in POST[item_key] always integer
unset($data[$i]);
}
$i++;
}
file_put_contents('data.json', json_encode(array_values($data)));
}
$_POST['item_key']
将在 html 中提交表单后出现,见下文。在您的 html 代码中,您需要添加以下内容:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nazwa</th>
<th scope="col">Cena</th>
<th scope="col">Kupujący</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key =>
$value): ?>
<tr>
<td><?php echo $value['id']; ?></td>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['price']; ?></td>
<td><?php echo $value['buyer']; ?></td>
<td>
<!-- action="#" means you will stay in the same script after submit -->
<form action="#" method="POST">
<input
hidden
type="text"
name="item_key"
value="<?php echo $value['id'];?>"
/>
<input type="submit" value="Remove" />
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
更新
unset
与array_values
之后一起使用json_decode
- 删除
header(refre..)
,因为刷新将通过表单提交到同一脚本完成
推荐阅读
- node.js - Jest Typescript with ES Module in node_modules 错误 - 必须使用导入来加载 ES 模块:
- docker - 我可以在 Docker Compose 中使用主机名构建插值字符串吗?
- reactjs - 如何将单选按钮添加到 react-sortable-tree?
- javascript - 在原点旋转一个矩形
- reactjs - 为什么我的 Next.JS 页面在再次查看页面时不会重新运行 javascript?
- python - 查找字符串中出现频率最高的单词并检查字符串是否仅包含 [az][AZ] 字符
- flutter - Flutter 中列表视图构建器的快照长度 [已修复]
- javascript - 使用 luxon 方法 fromFormat 无法按预期工作
- spring-boot - 证书在一台计算机上有效,但在另一台计算机上无效
- pandas - 将一列的选定值替换为另一列的中值但具有条件