首页 > 解决方案 > 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];
    }

?>

标签: php

解决方案


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.


推荐阅读