I'm having a user input an item, and that item is being added to an array and displayed as it goes. How might I add a quantity field and also display this quantity next to the item? Thank you!
我正在为用户输入一个项目,并且该项目正在添加到数组中并在显示时显示。如何添加数量字段并在项目旁边显示此数量?谢谢!
<form method="post">
`Add a new item: <input type="text" name="new_name"/>
<input type="submit"/>
<?php
$names = postVar('names') ? : array();
$names[] = postVar('new_name');
foreach ($names as $name) {
echo $name . "<br/>";
echo "<input type='hidden' name='names[]' value='$name'/>";
}
echo "Current items on list";
function postVar($name) {
// only if exists
if (! isset($_POST[$name])) {
return null;
}
// fetch
$out = $_POST[$name];
// cleanup
if (is_array($out)) {
return array_map('htmlspecialchars', $out);
}
return htmlspecialchars($out);
}
?>
</form>
1 个解决方案
#1
I know you're doing this for testing and learning, so I won't go into details. In short:
我知道你这是为了测试和学习,所以我不会详细介绍。简而言之:
-
Change line 2 from
改变第2行
`Add a new item: <input type="text" name="new_name"/>
to
`Add a new item: <input type="text" name="new_name"/>, <input type="text" name="qty"/> pcs
-
Change lines 7-9 from
改变第7-9行
$names[] = postVar('new_name'); foreach ($names as $name) { echo $name . "<br/>";
to
$names[postVar('new_name')] = postVar('qty'); foreach ($names as $name => $qty) { echo $name . ", qty: " . $qty . "<br/>";
I let you figure out yourself - this is the best way to learn. Read about arrays in PHP Manual.
我让你弄清楚自己 - 这是最好的学习方法。阅读PHP手册中的数组。
#1
I know you're doing this for testing and learning, so I won't go into details. In short:
我知道你这是为了测试和学习,所以我不会详细介绍。简而言之:
-
Change line 2 from
改变第2行
`Add a new item: <input type="text" name="new_name"/>
to
`Add a new item: <input type="text" name="new_name"/>, <input type="text" name="qty"/> pcs
-
Change lines 7-9 from
改变第7-9行
$names[] = postVar('new_name'); foreach ($names as $name) { echo $name . "<br/>";
to
$names[postVar('new_name')] = postVar('qty'); foreach ($names as $name => $qty) { echo $name . ", qty: " . $qty . "<br/>";
I let you figure out yourself - this is the best way to learn. Read about arrays in PHP Manual.
我让你弄清楚自己 - 这是最好的学习方法。阅读PHP手册中的数组。