0

I am getting a lot of data from a form through POST. As an example, here is some of the data:

event_date:

Array (
    [0] => 2017-04-02
    [1] => 2017-04-02
    [2] => 2017-04-03 )

equipment_name:

Array
(
    [0] => Array
        (
            [0] => Mic
            [1] => Sound System
            [2] => Wireless Mic
            [3] => Two Point Stage Wash
        )

    [1] => Array
        (
            [0] => Sound System
        )

    [2] => Array
        (
            [0] => Projection Package
            [1] => Gobo
            [2] => Audio Engineer
        )
)

To save this data I am doing two foreach loops:

foreach ($_POST['event_date'] as $key => $date) {
    echo "event number [".$key."]<br>";
    //insert into table value $_POST['event_date'][$key]

    foreach ($_POST['equipment_name'] as $ekey => $value) {
        echo "equipment number [".$key."][".$ekey."]<br>";
        //insert into table value $_POST['equipment_name'][$key][$ekey];
    }
}

Unfortunately my result is the following:

event number [0]
   equipment number [0][0]
   equipment number [0][1]
   equipment number [0][2]
event number [1]
   equipment number [1][0]
   equipment number [1][1]
   equipment number [1][2]
event number [2]
   equipment number [2][0]
   equipment number [2][1]
   equipment number [2][2]

As you can notice, the nested key ($ekey) equals the first key, not showing items over that number (eg: equipment number [0][3]), and saving nothing if the amount of equipment is lower than that number (eg: equipment number [1][1] and [1][2]).

Why the nested loop has this behavior? How could I solve this issue?

1 Answer 1

2

If I understood your question right, I think you want to access a particular nested array from $_POST['equipment_name'], yet you always access the outer array. This is a simple fix, change your second foreach to:

foreach ($_POST['equipment_name'][$key] as $ekey => $value) {
                                 ^^^^^^
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my... I spent the last two hours working this out for you to solve it in 10 seconds! Thank you very much , sidyll!
@cbarg glad to help! :)

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.