如何更改数组中的值?

时间:2019-05-20 19:29:12

标签: php html forms

我有以下代码(我只能使用HTML和PHP),其目的是根据在表单上显示并显示在同一页面上的操作来更改每个单元格的字母;问题是它没有实现其目标,它尝试了几种方法,但是没有一种起作用。有人可以帮我吗?

代码1: index.php

<body>
    <center>
        <?php
            require('action.php');

            tables();
            actions();

            echo '<form>';
            echo '<label>Row: <input  name="row" method="post"></label><br/>';
            echo '<label>Place: <input name="place" method="post"></label><br/>';

            echo '<br/>Operation: <select name="select">';
            echo '<option>reserve</option>';
            echo '<option>buy</option>';
            echo '</select>';
            echo '<button type="submit" name="btn" formmethod="post">send</button>';
            echo '</form>';
        ?>
    </center>
</body>

代码2: tables.php

<?php
    function tables(){
        $seating = array(
            array('', 1, 2, 3, 4, 5),
            array(1, 'L', 'L', 'L', 'L', 'L'),
            array(2, 'L', 'L', 'L', 'L', 'L'),
            array(3, 'L', 'L', 'L', 'L', 'L'),
            array(4, 'L', 'L', 'L', 'L', 'L'),
            array(5, 'L', 'L', 'L', 'L', 'L')
        );
        echo '<table style="border: 1px solid black;">';
        for ($i=0; $i < 6; $i++) {
            echo '<tr>';
            for ($j=0; $j < 6; $j++) {
                echo '<td>'.$seating[$i][$j].'</td>';
            }}
        echo '</tr>';
        echo '</table>';
    }
?>

代码3: action.php

<?php

    require('tablas.php');

    function actions(){
        if(isset($_POST["btn"])){
            if ($_POST["select"]=="reserve") {
                    $asientos[$_POST["row"]][$_POST["place"]]="R";
            }elseif ($_POST["select"]=="buy") {
                    $asientos[$_POST["row"]][$_POST["place"]]="L";
            }
        }
    }
?>

2 个答案:

答案 0 :(得分:1)

您有一个不含method的表单,因此默认为GET,但是您正在使用POST。按钮中有某种方法,但这是不正确的:

<!-- This: -->
<button type="submit" name="btn" formmethod="post">send</button>

<!- Should be: -->
<form method="post">
    <button type="submit" name="btn">send</button>
</form>

以下内容更多是代码审查,由于您的代码有改进的余地,我将对其进行几次编辑:

  • 请勿使用<center>。那已经过时了,请尝试<div style="text-align: center">
  • 您的while表单现在是PHP中的回显。这很混乱,这样您就错过了代码着色的好处,例如答案。您可以这样做:

    ?><!-- Stop here, continue as html -->
    <form method="post">
        Your other inputs here
        <input name="example" value="See my pretty colors?" />
        <!-- well, it's weird here on SO, but you get the gist -->
    </form>
    <?php
    
  • 函数不应回显信息,而应构建一些html并将其返回。这将创建更多可管理的代码,您可以在其中控制发生的事情。

    function tables(){
        $resulthtml = '';
        $resulthtml.= '<table style="border: 1px solid black;">';
        for ($i=0; $i < 6; $i++) {
            $resulthtml.= '<tr><td>'.$i.'</td></tr>';
        }
    
        return $resulthtml;
    }
    echo tables();
    

我将保留此内容,因为这不是评论网站,但是上述建议应该可以使您的代码更简洁,更易于理解,并且更容易通过扩展进行调试。

答案 1 :(得分:0)

我可以在 action.php 中看到的一个错字是:

require(' tablas.php ');

应为:     require(' tables.php ');

相关问题