猿问

如何在php中通过输入Html动态地将数据添加到数组中

我的问题是,如何通过 HTML 输入将数据添加到数组中,不仅是一个值,而且添加我想要的数量


<body>

    <form action="oop.php" method="post">

        <input type="number" name="no[]">

        <input type="number" name='no[]">

        <input type="number" name="no[]">

        <input type="submit" name="sub">

    </form> 

</body>

</html>

<?php

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

    $no= $_POST['no'];

    $ex = explode(",", $no);

    $item = array ();

    foreach ($ex as $item) {

        echo $item; // Do something with item

        print_r($item);

    }

}

?>

提前致谢


哈士奇WWW
浏览 187回答 3
3回答

万千封印

你做对了。您只需要在 foreach 循环之外打印项目值。在循环内它总是打印最后一个值<?phpif (isset($_POST['sub'])) {&nbsp; $no= $_POST['no'];&nbsp;// $ex = explode(",", $no);&nbsp; $items = array ();&nbsp; foreach ($no as $item) {&nbsp; &nbsp; &nbsp; echo $item; // Do something with item&nbsp; &nbsp; &nbsp; &nbsp;$items[] = $item;&nbsp; &nbsp;}&nbsp; &nbsp;print_r($items);}?>

Qyouu

当您使用此模式no[]时,您将发送一个数组,因此无需使用爆炸。该行也不$item = array ();执行任何操作,因为您正在填写 $itemforeach。因此,更改您的代码如下:<body><form action="array_check.php" method="post">&nbsp; &nbsp; <input type="number" name="no[]">&nbsp; &nbsp; <input type="number" name="no[]">&nbsp; &nbsp; <input type="number" name="no[]">&nbsp; &nbsp; <input type="submit" name="sub"></form></body></html><?phpif (isset($_POST['sub'])) {&nbsp; &nbsp; $no = $_POST['no'];&nbsp; &nbsp; foreach ($no as $item) {&nbsp; &nbsp; &nbsp; &nbsp; echo $item ; // Do something with item&nbsp; &nbsp; &nbsp; &nbsp; print_r($item);&nbsp; &nbsp; }}

拉风的咖菲猫

这应该可以做到:<?phpif (isset($_POST['sub'])) {&nbsp; &nbsp; $no= $_POST['no'];&nbsp; &nbsp; $nos = explode(",", $no);&nbsp; &nbsp; $items = array (); // careful here you are using $item twice !&nbsp; &nbsp; foreach ($nos as $no) {&nbsp; &nbsp; &nbsp; &nbsp; $items[] = $no;&nbsp; &nbsp; }&nbsp; &nbsp; var_dump($items);}?>
随时随地看视频慕课网APP

相关分类

Go
我要回答