PHP。为数组中未选中的框创建值

时间:2011-08-18 09:18:08

标签: php

我有以下表格:

<form action="update-table.php" method="post">
<table class="table-data" border="1">
    <thead>
        <tr>
            <td>ID</td>
            <td>Live</td>
            <td>User</td>
            <td>Last Update</td>
            <td>Title</td>
            <td>Content</td>
            <td>Edit</td>
            <td>Delete</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="1" /></td>
            <td><input name="live[]" type="checkbox" checked="checked" value="1"/></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:10 am</td>
            <td>Title1</td>
            <td>Content1</td>
            <td><a href="edit-news.php?editID=1">Edit</a></td>
            <td><a href="delete-news.php?deleteID=1">Delete</a></td>
        </tr>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="2" /></td>
            <td><input name="live[]" type="checkbox" /></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:11 am</td>
            <td>Title2</td>
            <td>Content2</td>
            <td><a href="edit-news.php?editID=2">Edit</a></td>
            <td><a href="delete-news.php?deleteID=2">Delete</a></td>
        </tr>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="3" /></td>
            <td><input name="live[]" type="checkbox"/></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:10 am</td>
            <td>Title3</td>
            <td>Content3</td>
            <td><a href="edit-news.php?editID=3">Edit</a></td>
            <td><a href="delete-news.php?deleteID=3">Delete</a></td>
        </tr>
    </tbody>
</table>
<input type="submit" />

我要做的是使用$_POST显示数组发送。

问题是未选中复选框时 - 没有发送任何内容。

如何检查是否设置了$_POST['live'],如果没有 - 将其值设置为0?

以下代码不起作用。为什么?

if (!isset($_POST['live'])) {
            $_POST['live'] = "0";
        }


        for ($i=0;$i<count($_POST['id']);$i++) {

          echo "<p>".$_POST['id'][$i]."</p>";
          echo "<p>".$_POST['live'][$i]."</p>";
          echo "<hr />";

        } 

1 个答案:

答案 0 :(得分:1)

试试这个:

for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    }

    echo "<p>".$_POST['id'][$i]."</p>";
    echo "<p>".$_POST['live'][$i]."</p>";
    echo "<hr />";
}