php 从表单发布多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1719087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:36:51  来源:igfitidea点击:

multi-dimensional array post from form

phpjqueryxhtmlformspost

提问by Basit

I want to know how i can post a multi-dimensional array?

我想知道如何发布多维数组?

Basically i want to select a user and selected user will have email and name to sent to post.

基本上我想选择一个用户,选定的用户将有电子邮件和姓名发送到帖子。

So selecting 100 users, will have email and name. I want to get in PHP like following

所以选择 100 个用户,将有电子邮件和姓名。我想像下面这样进入 PHP

$_POST['users'] = array(
  array(name, email),
  array(name2, email2),
  array(name3, email3)
);

Any ideas?

有任何想法吗?

回答by Franz

You can name your form elements like this:

您可以像这样命名表单元素:

<input name="users[1][name]" />
<input name="users[1][email]" />
<input name="users[2][name]" />
<input name="users[2][email]" />
...

You get the idea...

你明白了...

回答by cregox

Here's another way: serializethe array, post and unserialize(encrypting optional).

是另一种方式:序列化数组,发布和反序列化(加密可选)。

And here's an example that worked for me:

这是一个对我有用的例子:

"send.php":

发送.php”:

<input type="hidden" name="var_array" value="<?php echo base64_encode(serialize($var_array)); ?>">

"receive.php":

接收.php”:

if (isset($_POST['var_array'])) $var_array = unserialize(base64_decode($_POST['var_array']));

With that you can just use $var_arrayas if it were shared between the two files / sessions. Of course there need to be a <form>in this send.php, but you could also send it on an <a>as a query string.

有了它,您就可以$var_array像在两个文件/会话之间共享一样使用它。当然<form>,这个send.php 中需要有 a ,但您也可以将它<a>作为查询字符串发送。

This method has a big advantage when working with multi-dimensional arrays.

这种方法在处理多维数组时有很大的优势。

回答by Benjamin Cox

Well, you are going to have to do some looping somewhere. If you name each form element with an index (as Franz suggests), you do the looping on the PHP side.

好吧,你将不得不在某处做一些循环。如果您使用索引命名每个表单元素(如 Franz 建议的那样),则您在 PHP 端执行循环。

If you want to use Javascript to do the looping, have your form onSubmit() create a JSON string to pass to the PHP. Then have the PHP retrieve it like so:

如果您想使用 Javascript 进行循环,请让您的表单 onSubmit() 创建一个 JSON 字符串以传递给 PHP。然后让 PHP 像这样检索它:

json_decode($_POST['users'], true);

The second argument tells it to make arrays instead of anonymous objects.

第二个参数告诉它创建数组而不是匿名对象。