关联多维数组

时间:2014-10-15 19:48:31

标签: php arrays multidimensional-array

我希望能够在一个变量中使用一个变量(这是一个在文本框中估算的值)  关联多维数组并打印出与其关联的其余数组值。

这是我迄今为止所做的不起作用

<html>
<body>
<form method="post" action="newcal.php">

<table>
<tr>
    <td> Item #: </td>
    <td> <input type=text name= txtitem > <br> </td>

    <td>
    </td>
    <td> <fieldset style = "width:60px">
        <input type=submit value = "Get Data" name= getdata>
        <input type=submit value = "Add to Cart" name= addto>
        <input type=submit value = "Get Total" name= gettotal>
        </fieldset>
        </td>
</tr>
</table>
</form>

<?php
$item = isset($_POST['txtitem']);


$stuff = array(
             array("id" => 1,"name" => "Apples","price" => 50 ),
             array("id" => 2,"name" => "Pineapples","price" => 125 ),
             array("id" => 3,"name" => "Mango","price" => 35 ),
             array("id" => 4,"name" => "Banana","price" => 25 ),
             array("id" => 5,"name" => "Naseberry","price" => 38 ));


            if(isset($_POST['getdata']))
            {

                foreach ($stuff as $row) 
                {
                    if ($row['id'] == $item) 
                    {
                        $name = $row['name'];
                        $price = $row['price'];

                    }
                }
            echo $name;
            echo $price;
            }


?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我认为你的错误是以下一行:

$item = isset($_POST['txtitem']);

$ item被设置为布尔值。你可能想要这样的东西:

$item = (isset($_POST['txtitem']) ? intval($_POST['txtitem']) : null);