php - PHP Arrays,foreach 无法访问完整的数组元素
问题描述
我在使用 foreach 循环访问数组元素时遇到问题。
<?php
echo "<form method=post action=test.php>";
echo "Item Name: <input type=text name=item[]>";
echo "Price: <input type=text name=item[]>";
echo "Quantity: <input type=text name=item[]>";
echo "<BR>";
echo "<BR>";
echo "<input type=submit name=submit>";
if (isset ($_POST['item']))
{
$item = $_POST['item'];
}
$item = array (
$item_name = $item [0],
$price = $item [1],
$qty = $item [2],
);
foreach ($item as $item)
{
echo $item[0];
echo $item[1];
echo $item[2];
}
?>
解决方案
Simple way, is to rename your <input type=text
by needable fields(name, price, qty) and then get data from $_POST by their names:
echo "<form method=post action=test.php>";
echo "Item Name: <input type=text name='name'>";
echo "Price: <input type=text name='price'>";
echo "Quantity: <input type=text name='qty'>";
echo "<BR>";
echo "<BR>";
echo "<input type=submit name=submit>";
$name = "";
if (isset ($_POST['name']))
{
$name = $_POST['name'];
}
$price = "";
if (isset ($_POST['price']))
{
$price = $_POST['price'];
}
$qty = "";
if (isset ($_POST['qty']))
{
$qty = $_POST['qty'];
}
If you want to use more flexible method with possible list of input fields, then create array of keys with possible field's names and check all existence each key in foreach loop:
$all_possible_items_keys = ["name","price","qty","author"];
$items = [];
foreach ( $all_possible_items_keys as $key )
{
if (isset ($_POST[$key]))
{
$items[$key] = $_POST[$key];
}
}
print_r($items);
Output example:
Array ( [name] => 11 [price] => 11 [qty] => 22 ):
Add names to your <input type=text
and add it to $all_possible_items_keys
, then $items
will hold keys=>value.
推荐阅读
- label - Gnuplot,热图,标记某个点
- angular - 从 catchError 中的返回 observable 中获取值
- corda - Corda 在 Java 中遍历事务链
- json - 仅当不在 Unity 3D 播放器中调试时出现 NullReference 错误
- vba - 根据excel中的列表将PDF文件移动到特定文件夹
- android - debug.keystore 丢失。无法在 .androdid 文件夹中找到它
- amazon-web-services - 使用boto3从sqs接收和删除消息
- jquery - 将嵌套的 JSON 对象转换为 Accordion 格式
- rest - gitlab api:获取一个组的所有项目(带有子组)
- c# - 在 MVC 中创建数据库类