如何使用 HTML 中的单选按钮显示可变数量的项目?
How can I display a variable number of items using radio buttons in HTML?
file.json: {"items":[{"num":1,"color":"red"} ,{"num":2,"color":"blue"}]}
Objective: 使用 PHP 读取 file.json 并从数组中删除对象并保存。
方法: 我正在读取文件并在单选按钮旁边显示数组项。与所选单选按钮对应的对象被删除。
代码:
<?php
$myfile = fopen("/home/user/php/".$filename,"r" ) or die("unable to open file");
$myjsonstr = fread($myfile, filesize("/home/user/php/".$filename));
fclose($myfile);
$jsons = json_decode($myjsonstr, true);
?>
<form action="delete.php" method="POST">
<input type="radio" name="testcase" value="1"> <?php print_r($jsons["testcases"][0]);?>
<input type="radio" name="testcase" value="2"> <?php print_r($jsons["testcases"][1]);?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
问题: 我需要使列表的长度动态化,因为 "items" 的值字段可以有可变数量的对象。但似乎 HTML 中的单选按钮数量不能可变。正如您从代码片段中看到的那样,没有。单选按钮的数量始终为 2。如果我的 JSON 中的数组有 3 个对象而不是 2 个,我将不得不更改代码。
可能吗?怎么样?
谢谢,prime_mover!额外的细节会有所帮助。假设 json_decode 之前的部分是正确的,并且变量 $jsons 中有一个解码对象。
为了简洁起见,我们也将测试用例放在它们自己的变量中。
<?php
$testCases = $jsons["testcases"]; // array of indeterminate length
?>
<form action="delete.php" method="POST">
<?php
foreach ($testCases as $ix => $caseTxt) {
$v = $ix+1;
?>
<input type="checkbox" name="testcase" value="<?=$v;?>" /><?php print_r($caseTxt); echo "<br>"; ?><br>
<?php } ?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
循环为 $testCases 数组中的每个条目写入一个新输入。
并不是说这是完美的代码,也不是说它完全符合您的要求,但它确实可以处理未知长度的列表。
您可能希望以不同方式处理零长度。
注意我将类型更改为复选框,因为你下面的文字说 "Delete Selected Values" 所以我猜你想允许多个选择。
file.json: {"items":[{"num":1,"color":"red"} ,{"num":2,"color":"blue"}]}
Objective: 使用 PHP 读取 file.json 并从数组中删除对象并保存。
方法: 我正在读取文件并在单选按钮旁边显示数组项。与所选单选按钮对应的对象被删除。
代码:
<?php
$myfile = fopen("/home/user/php/".$filename,"r" ) or die("unable to open file");
$myjsonstr = fread($myfile, filesize("/home/user/php/".$filename));
fclose($myfile);
$jsons = json_decode($myjsonstr, true);
?>
<form action="delete.php" method="POST">
<input type="radio" name="testcase" value="1"> <?php print_r($jsons["testcases"][0]);?>
<input type="radio" name="testcase" value="2"> <?php print_r($jsons["testcases"][1]);?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
问题: 我需要使列表的长度动态化,因为 "items" 的值字段可以有可变数量的对象。但似乎 HTML 中的单选按钮数量不能可变。正如您从代码片段中看到的那样,没有。单选按钮的数量始终为 2。如果我的 JSON 中的数组有 3 个对象而不是 2 个,我将不得不更改代码。
可能吗?怎么样?
谢谢,prime_mover!额外的细节会有所帮助。假设 json_decode 之前的部分是正确的,并且变量 $jsons 中有一个解码对象。 为了简洁起见,我们也将测试用例放在它们自己的变量中。
<?php
$testCases = $jsons["testcases"]; // array of indeterminate length
?>
<form action="delete.php" method="POST">
<?php
foreach ($testCases as $ix => $caseTxt) {
$v = $ix+1;
?>
<input type="checkbox" name="testcase" value="<?=$v;?>" /><?php print_r($caseTxt); echo "<br>"; ?><br>
<?php } ?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
循环为 $testCases 数组中的每个条目写入一个新输入。 并不是说这是完美的代码,也不是说它完全符合您的要求,但它确实可以处理未知长度的列表。
您可能希望以不同方式处理零长度。
注意我将类型更改为复选框,因为你下面的文字说 "Delete Selected Values" 所以我猜你想允许多个选择。