如何创建一个php二维数组?

时间:2013-04-10 20:33:27

标签: php arrays

大家好我是php的新手,我必须完成一个我正在做的PHP课程的作业,但我在理解它时遇到了一些麻烦。

基本上我必须使用循环和字符串创建一个带有以下输出的程序:

a 00000000
b 00000000
c 00000X00
d 00000000
e 00000000
f 000X0000
g 00000000
h 00000X00
  12345678

“用户在开头输入二维字符串。基于此字符串(坐标)在表格上绘制”x“。”

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

我完全同意@Marc B你需要做自己的功课。您可以在php.net网站上了解PHP数组以及如何使用它们:http://us3.php.net/manual/en/book.array.php以及此处:http://www.w3schools.com/php/php_arrays.asp

答案 1 :(得分:0)

使用循环(While,For,Foreach)可以自动生成多阵列,但是你可以解决这些问题。这是一种手动方式:

 $array = array('a'=>array(1 => 0,2 => 0,3 => 0,),'b'=>array(1 => 0,2 => 0,3 => 0,));

然后你需要构建一个html输入并使用$ _GET或$ _POST接收输入

使用该输入来决定Marc B所说的做法:

 $array[$y][$x] = 'X';

答案 2 :(得分:0)

我想你想要像this这样的东西。

源代码:

        <?php
            $Y = range('a', 'h');
            $X = range(1, 8);
        ?>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
            <div id="in">Coord X: <input type="number" min="1" max="8" name="x" value="<?php echo $X[array_rand($X)]; ?>"></div>
            <div id="in">Coord Y: <input type="text" name="y" value="<?php echo $Y[array_rand($Y)]; ?>"></div>
            <br /><input id="subm" type="submit" value="DRAW!">
            <input name="reset" id="reset" type="submit" value="reset">
        </form>
        <table>
            <tfoot>
                <tr>
                    <td></td><?php foreach($X as $x) echo "<td><strong>$x</strong></td>"; ?>
                </tr>
            </tfoot>
            <tr>
                <?php
                    if(isset($_GET['reset']))
                    {
                        session_destroy();
                        header('Location: thisPage.php');
                    }
                    $coords = !empty($_GET) ? $_GET['x'].$_GET['y'] : NULL;
                    $_SESSION['coords'][] = $coords;
                    for($i = 0; $i < count($Y); $i++)
                    {
                        echo "<tr><td><strong>$Y[$i]</strong></td>";
                        for($j = 0; $j < count($Y); $j++)
                        {
                            if(isset($_GET) && in_array($X[$j].$Y[$i], $_SESSION['coords']))
                            {
                                echo '<td id="ex"><strong>X</strong></td>';
                            }
                            else
                            {
                                echo '<td>0</td>';
                            }
                        }
                    }
                    echo "</tr>";
                ?>
            </tr>
        </table>
相关问题