user966582
user966582

Reputation: 3323

group data of multiple fields in an array

I have some hidden input values for each module as you see in following HTML. Once the data is posted, how can I get the data of each module in an array, so that I can store it.

<div class="module">Module1</div>
<input type="hidden" value="module1" name="module_id">
<input type="hidden" value="title" name="title">
<input type="hidden" value="some text" name="text">

<div class="module">Module2</div>
<input type="hidden" value="module2" name="module_id">
<input type="hidden" value="another title" name="title">
<input type="hidden" value="another text" name="text">

I am unable to understand how to combine the title and the text input together with their module id.

Upvotes: 1

Views: 201

Answers (3)

Rahul
Rahul

Reputation: 1181

Try This

<div class="module">Module1</div>
<input type="hidden" value="module1" name="module_id[]">
<input type="hidden" value="title" name="title[]">
<input type="hidden" value="some text" name="text[]">

<div class="module">Module2</div>
<input type="hidden" value="module2" name="module_id[]">
<input type="hidden" value="another title" name="title[]">
<input type="hidden" value="another text" name="text[]">

To extract value use:

$_POST['module_id'][0] // to access id from module 1

$_POST['module_id'][1] // to access id from module 2

And the same way you can access others :)

Upvotes: 2

Barmar
Barmar

Reputation: 781380

Put [] after the names. PHP will turn them each into an array.

<div class="module">Module1</div>
<input type="hidden" value="module1" name="module_id[]">
<input type="hidden" value="title" name="title[]">
<input type="hidden" value="some text" name="text[]">

<div class="module">Module2</div>
<input type="hidden" value="module2" name="module_id[]">
<input type="hidden" value="another title" name="title[]">
<input type="hidden" value="another text" name="text[]">

Now you'll have arrays $_POST['module_id'], $_POST['title'], and $_POST['text'] that you can iterate over.

Upvotes: 2

MosheK
MosheK

Reputation: 1196

Try this:

<div class="module">Module1</div>
<input type="hidden" value="module1" name="module[0][module_id]">
<input type="hidden" value="title" name="module[0][title]">
<input type="hidden" value="some text" name="module[0][text]">

<div class="module">Module2</div>
<input type="hidden" value="module2" name="module[1][module_id]">
<input type="hidden" value="another title" name="module[1][title]">
<input type="hidden" value="another text" name="module[1][text]">

...

And you can access it like so:

foreach ($_POST['module'] as $module) {
    echo $module['module_id'];
    echo $module['title'];
    echo $module['text'];
}

Upvotes: 3

Related Questions