max max
max max

Reputation: 55

How to parse the data of multiple items with multiple inputs for each in HTML form?

I have this HTML form:

<form>
    <div>
        <h1>Item 1</h1>
        <input name="item_title[]" value="Any 1">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
    </div>
    <div>
        <h1>Item 1</h1>
        <input name="item_title[]" value="Any 2">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
    </div>
    <div>
        <h1>Item 3</h1>
        <input name="item_title[]" value="Any 3">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
        <input name="phone[]" placeholder="phone number">
    </div>
    ...
</form>

On server side, in PHP for example I can loop through item_title[] to know each item:

foreach($_POST['item_title'] as $key => $value){
    $item_order = $key; // or $key + 1
    $item_title = $value;
}

my problem is that I get a item_title array with 3 elements and a phone array will 9 elements but what I really want is to get:

item_title: phone1, phone2, phone3 // 1
item_title: phone1, phone2, phone3 // 2
item_title: phone1, phone2, phone3 // 3

so I can loop each time on item_title array and get the 3 phone numbers respectively to the items.

I hope my idea is clear :/

Thank you!

Upvotes: 0

Views: 188

Answers (3)

msg
msg

Reputation: 8171

If you can index your inputs, you can use multidimensional arrays:

<input name="item_title[0]" value="Any 1">
<input name="phone[0][]" placeholder="phone number">
<input name="phone[0][]" placeholder="phone number">
<input name="phone[0][]" placeholder="phone number">

And process them in php:

foreach($_POST['item_title'] as $key => $value){
    $item_title = $value;
    // Output formatted as in your example, but you can loop the array
    echo $item_title . ': ' . implode(',', $_POST['phone'][$key]);
}

Hope it helps

Upvotes: 1

user11130345
user11130345

Reputation:

You can use seelct2 check multiple select box option. For inserting multiple value.

Upvotes: 0

cli-ish
cli-ish

Reputation: 776

A solution would be that you create seperate phone names like this :

<div>
    <h1>Item 2</h1>
    <input name="item_title[]" value="Any 2">
    <input name="phone1[]" placeholder="phone number">
    <input name="phone2[]" placeholder="phone number">
    <input name="phone3[]" placeholder="phone number">
</div>
<div>
    <h1>Item 1</h1>
    <input name="item_title[]" value="Any 1">
    <input name="phone1[]" placeholder="phone number">
    <input name="phone2[]" placeholder="phone number">
    <input name="phone3[]" placeholder="phone number">
</div>

Upvotes: 1

Related Questions