通过在POST var名称中提供数组键,将PHP POST vars用作关联数组

时间:2012-09-13 16:42:12

标签: php associative-array

PHP开发人员知道名称后附带[]的字段将生成一个值数组。例如

<input type="hidden" name="gift[]" value="Jerry Garciuh" />
<input type="hidden" name="gift[]" value="Gulf South Thingamabob" />

将产生

Array
(
    [gift] => Array
        (
            [1] => Jerry Garciuh
            [2] => Gulf South Thingamabob
        )

)

但我最近了解到这可以更进一步:

2 个答案:

答案 0 :(得分:3)

这是新的吗? O.o 在2003年左右,我使用这种方式制作4-6维数组来保存cms的设置

答案 1 :(得分:2)

通过在字段名称中提供键值,如下所示:

<form action="" method="post" id="gr" >
<input type="hidden" name="api_key" value="foobarbaz" />
<input type="hidden" name="gift[amount]" value="1" />
<input type="hidden" name="gift[recipient_email]" value="jerrygarciuh@example.com" />
<input type="hidden" name="gift[recipient_name]" value="Jerry Garciuh" />
<input type="hidden" name="gift[sender_name]" value="Gulf South Thingamabob" />
<input type="hidden" name="gift[message_announce]" value="Oh hai" />
<input type="submit" />
</form>

您可以为后端生成更高度组织的后期数据关联数组:

Array
(
    [api_key] => foobarbaz
    [gift] => Array
        (
            [amount] => 1
            [recipient_email] => jerrygarciuh@example.com
            [recipient_name] => Jerry Garciuh
            [sender_name] => Gulf South Thingamabob
            [message_announce] => Oh hai
        )

)