PHP:当名称没有数组时检索复选框的值 [英] PHP: Retrieving value of checkboxes when name doesn't have array

查看:132
本文介绍了PHP:当名称没有数组时检索复选框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个表单我没有任何控制是POST数据到我的PHP脚本。表单包含沿这些行的复选框:

A form I don't have any control over is POSTing data to my PHP script. The form contains checkboxes along these lines:

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

如果我要写表单的代码,我会写 name =option []而不是 name =option。但这不是我能做的改变。现在,如果两个复选框都被选中, $ _ POST [option] 只返回一个值。我如何在PHP中检索所有选择的值?

If I were to write the code for the form, I'd write name="option[]" instead of name="option". But this is not a change I can do. Now, if both checkboxes are checked, $_POST["option"] returns just one of the values. How can I, in PHP retrieve all the values selected?

推荐答案

例如:

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

选中两个框,输出将是:

Check both boxes and the output will be:

option=val1&option=val2

现场演示。所有你需要做的就是自己解析字符串,以一种合适的格式。下面是一个函数的例子:

Here's a live demo. All you have to do then is to parse the string yourself, into a suitable format. Here's an example of a function that does something like that:

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

输出:

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

)

可能有几种情况下,此功能无法按预期工作,请小心。

There might be a few cases where this function doesn't work as expected though, so be careful.

这篇关于PHP:当名称没有数组时检索复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆