1

I've got a dynamic form that allows a user to create as many form elements as they need -- then submit them. For this, I have prepared the input names as arrays like

<input name="title[]" ...

and posting them gives me output like

Array
(
[day] => 0
[project_id] => 5
[submit] => publish
[id] => Array
    (
        [0] => 4
        [1] => 5
    )

[title] => Array
    (
        [0] => Step 1
        [1] => Step 2
    )

[max_vol] => Array
    (
        [0] => 2
        [1] => 3
    )

[description] => Array
    (
        [0] => df dofi dofidfoi 
        [1] => dfvpdofvdpfo osd pod 
    )

)

I've created something that allows me to just grab the post arrays like so

foreach( $_POST as $post_key ) {
    // ignore non-array post variables
    if( is_array( $post_key ) ) {
        foreach( $post_key as $form_value ) {
            echo "$form_value\n";
        }
    }
}

/* ouputs...
4
5
Step 1
Step 2
2
3
df dofi dofidfoi 
dfvpdofvdpfo osd pod 
*/

which nicely sorts the non-arrays from the arrays, but I can't figure out how to take this variable number of created form elements and prepare them into an array variable that looks something like...

Array
(
  [0] => Array
  (
      'id' => 4, 'title' => 'Step 1', 'max_vol' => '2', 'description' => 'df dofi dofidfoi'
  ),
  [1] => Array
  (
      'id' => 5, 'title' => 'Step 2', 'max_vol' => '3', 'description' => 'dfvpdofvdpfo osd pod'
  ),
  // could be more or less elements...
);

(I will be eventually passing these arrays to a MySQL query builder function).

Thanks.

2 Answers 2

1

How about creating a variable that is outside the scope of the foreach loop

$results = array();
foreach( $_POST as $post_key=>$post_value ) {
    // ignore non-array post variables
    if( is_array( $post_value ) ) {
        foreach( $post_value as $form_key=>$form_value ) {
            if (!isset($results[$form_key]))
            {
                $results[$form_key] = array();
            }   
            $results[$form_key][$post_key] = $form_value;
        }
    }
}

// results is your array variable
print_r($results);
Sign up to request clarification or add additional context in comments.

Comments

1

Iterate over some significant $_POST-array key, for example - id and get the values from other $_POST-arrays with the same index:

$values = array();
foreach ($_POST['id'] as $k => $v) {
    $values[] = array(
        'id' => $v,
        'title' => $_POST['title'][$k],
        'max_vol' => $_POST['max_vol'][$k],
        'description' => $_POST['description'][$k],
    );
}

print_r($values);

Comments

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.