0

I have two dropdown option with same name like following.

<form action="" method="post">
    <select name="freeoptions[]">
        <option value="[7][4]">Black</option>
        <option value="[7][5]">Blue</option>
        <option value="[7][3]">Red</option>
    </select>


    <select name="freeoptions[]">
        <option value="[9][11]">Small</option>
        <option value="[9][15]">Large</option>
        <option value="[9][13]">XL</option>
    </select>

    <input type="submit" name="submit" value="submit">
</form>

Now when i am posting form, getting post data in array like,

Array
(
    [freeoptions] => Array
        (
            [0] => [7][4]
            [1] => [9][11]
        )
)

But I want this array something like

Array
        (
            [freeoptions] => Array
            (
                [0] => Array
                (
                        [id] => [7]
                        [value] => [4]
                )
                [1] => Array
                (
                        [id] => [9]
                        [value] => [11]
                )
            )
        )

Can anyone please help me how to do this. Thanks,

2 Answers 2

1

Anything in a "value" attribute is sent as a literal string, regardless of it's content, so you can't post a value as an array out of the box.

You can always have both values in the same value attribute and split it in the back end.

Example in HTML:

<option value="7;4"></option>

Then do something like this in your back end:

$data = [];

// Loop all freeoptions params
foreach ($_POST['freeoptions'] as $opt) {
    // Split the value on or separator: ;
    $items = explode(';', $opt);

    if (count($items) != 2) {
        // We didn't get two values, let's ignore it and jump to the next iteration
        continue;
    }

    // Create our new structure
    $data[] = [
        'id'    => $items[0], // Before the ;
        'value' => $items[1], // After the ;
    ];
}

The $data-array should now contain the data structure you want.

If you want to keep using the $_POST-variable instead, just overwrite the original data after the foreach:

$_POST['freeoptions'] = $data;
Sign up to request clarification or add additional context in comments.

Comments

0

Do you want to display result from database or display manually?

1 Comment

This is a comment, not an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.