PHP:当name没有数组时,检索复选框的值

ave*_*net 4 php checkbox post

我无法控制的表单是将数据POST到我的PHP脚本.表单包含以下行的复选框:

<input type="checkbox" value="val1" name="option"/>
<input type="checkbox" value="val2" name="option"/>
Run Code Online (Sandbox Code Playgroud)

如果我要编写表单的代码,我会写name="option[]"而不是name="option".但这不是我能做的改变.现在,如果选中了两个复选框,则只$_POST["option"]返回其中一个值.我如何在PHP中检索所有选定的值?

Emi*_*l H 14

您可以阅读原始帖子数据.例如:

<fieldset>
    <legend>Data</legend>
    <?php
    $data = file_get_contents("php://input");
    echo $data."<br />";
    ?>
</fieldset>

<fieldset>
    <legend>Form</legend>
    <form method="post" action="formtest.php">
        <input type="checkbox" value="val1" name="option"/><br />
        <input type="checkbox" value="val2" name="option"/><br />
        <input type="submit" />
    </form>
</fieldset>
Run Code Online (Sandbox Code Playgroud)

检查两个框,输出将是:

option=val1&option=val2
Run Code Online (Sandbox Code Playgroud)

这是一个现场演示.您所要做的就是自己解析字符串,使其成为合适的格式.这是一个函数的例子,它做了类似的事情:

function parse($data)
{
    $pairs = explode("&", $data);

    // process all key/value pairs and count which keys
    // appear multiple times
    $keys = array();
    foreach ($pairs as $pair) {
        list($k,$v) = explode("=", $pair);
        if (array_key_exists($k, $keys)) {
            $keys[$k]++;
        } else {
            $keys[$k] = 1;
        }
    }

    $output = array();
    foreach ($pairs as $pair) {
        list($k,$v) = explode("=", $pair);
        // if there are more than a single value for this
        // key we initialize a subarray and add all the values
        if ($keys[$k] > 1) {
            if (!array_key_exists($k, $output)) {
                $output[$k] = array($v);
            } else {
                $output[$k][] = $v;
            }
        } 
        // otherwise we just add them directly to the array
        else {
            $output[$k] = $v;
        }
    }

    return $output;
}

$data = "foo=bar&option=val1&option=val2";

print_r(parse($data));
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [foo] => bar
    [option] => Array
        (
            [0] => val1
            [1] => val2
        )

)
Run Code Online (Sandbox Code Playgroud)

可能有一些情况下这个功能不能按预期工作,所以要小心.

  • 根据您的PHP设置,您可能无法在php://输入流上使用file_get_contents.在这种情况下,您将需要使用fopen('php:// input','r')和stream_get_contents($ fp) (2认同)