Skip to content
Advertisement

Elegantly transform PHP multidimensional list of clolumns => values into database-like rows

I’m having a pretty hard time describing this in the title, I’m taking suggestions.

I have a form where I have a few inputs for contact data, named contact_names[], contact_emails[] and contact_phones[]. More fields can be dynamically added if more contacts are needed. Long story short, if the user informs 3 contacts, my $_POST will contain something like this:

JavaScript

I’d like to transform this into an array like this:

JavaScript

As that will help me inserting the rows into a table with columns contact_name, contact_email and contact_phone.

I currently have an implementation taking the count of contact_names and iterating through the data with a for loop and populating $contact_rows[$i], but I’ve been wondering if there’s a more elegant way of doing this with something like array_columns().

Advertisement

Answer

This must be the 100th answer, but just create your form as:

JavaScript

After that – print_r($_POST) and enjoy.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement