11

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

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

Any ideas?

Alexander
  • 23,432
  • 11
  • 63
  • 73
Basit
  • 16,316
  • 31
  • 93
  • 154
  • related: http://stackoverflow.com/questions/1548159/php-how-to-send-an-array-to-another-page/1548193#1548193 – cregox Feb 21 '11 at 19:22

3 Answers3

31

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

Franz
  • 11,353
  • 8
  • 48
  • 70
  • 2
    what about users[][name], do i have to set the id (1, 2..)? – Basit Nov 12 '09 at 00:48
  • 3
    Nope. You can go with `users[]`, too. – Franz Nov 12 '09 at 00:53
  • What about a situation where the number of users isn't predefined, say a user clicks a + button and a new set of fields opens and they can actually choose to not add any users – Pila Nov 13 '17 at 21:37
  • @Pila Does the previous comment help? – Franz Nov 27 '17 at 15:43
  • I ended up using jQuery to dynamically create new input fields with a name using a counter like so: name = "users["+i+"][name]" – Pila Nov 28 '17 at 10:31
7

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

And here's an example that worked for me:

"send.php":

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

"receive.php":

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

With that you can just use $var_array as 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.

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

Community
  • 1
  • 1
cregox
  • 17,674
  • 15
  • 85
  • 116
2

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.

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:

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

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

Benjamin Cox
  • 6,090
  • 21
  • 19