我有一个如下表:
<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>
更新
- 在
json_decode
之后将unset
与array_values
一起使用 - 删除了
header(refre..)
,因为刷新将通过表单提交到同一脚本来完成