Вопрос по checkbox, post, php – PHP: получение значения флажков, когда имя не имеет массива

4

Error: User Rate Limit Exceeded

<input type="checkbox" value="val1" name="option"/>
<input type="checkbox" value="val2" name="option"/>

Error: User Rate Limit Exceededname="option[]" вместоname="option"Error: User Rate Limit Exceeded$_POST["option"]Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded avernet
Error: User Rate Limit Exceeded Ian Elliott

Ваш Ответ

1   ответ
14

Error: User Rate Limit Exceeded

<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>

Error: User Rate Limit Exceeded

option=val1&option=val2

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

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));

Error: User Rate Limit Exceeded

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

)

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы