如何在HTML表单中创建此数组结构?

时间:2012-09-23 23:50:08

标签: php mysql arrays multidimensional-array

我有以下HTML表单,它是从MySQL数据库中的表动态生成的。

<form method="post" name="chapters" action="ChaptersUpdate.php">
<input type='text' name='id' value='{$row['id']}'>
<input type='text' name='name' value='{$row['name']}'>
<input type='password' name='password' value={$row['password']};>
<input type='submit'>
</form>

我正在寻找一种方法,使得在提交表单时,以下数据结构将在$ _POST中传递:

 [chapter] => Array
  (
    [0] => Array
        (
            [id] => corresponding chapter ID
            [name] => corresponding chapter name
            [password] => corresponding chapter password
        )

    [1] => Array
        (
            [id] => corresponding chapter ID
            [name] => corresponding chapter name
            [password] => corresponding chapter password
        )

)

我尝试了各种名称='chapter [] [id]'/ name ='chapter [] [name]'/ name ='chapter [] [password]'的组合,但收效甚微。数组数据结构看起来永远不像我想要的样子。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

以下似乎对我有用:

<input type='text' name='chapters[0][id]'>
<input type='text' name='chapters[0][name]'>
<input type='password' name='chapters[0][password]'>

<input type='text' name='chapters[1][id]'>
<input type='text' name='chapters[1][name]'>
<input type='password' name='chapters[1][password]'>

答案 1 :(得分:0)

您可以像这样创建表单

<form method="post" name="chapters">
<?php 
for($i = 0; $i <3; $i++)
{
    echo "ID: <input type='text'  name='chapters[$i][id]' /> <br />";
    echo "Name: <input type='text' name='chapters[$i][name]' /> <br />";
    echo "Password: <input type='text' name='chapters[$i][password]' /> <br /> ";
    echo "<Br />";
}
?>
<input type='submit'>
</form>

示例PHP

if(isset($_POST['chapters']))
{
    echo "<pre>";
    print_r($_POST['chapters']);
}

示例输出

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Name1
            [password] => Password1
        )

    [1] => Array
        (
            [id] => 2
            [name] => name 2
            [password] => password 2
        )

    [2] => Array
        (
            [id] => 2
            [name] => name 3
            [password] => Password
        )

)