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:

$_POST = [
    (...)
    'contact_names' => ['john', 'Ed', 'Paul'],
    'contact_emails' => ['john@gmail.com', 'ed@gmail.com', 'paul@gmail.com'],
    'contact_phones' => ['555-5555', '333-3333', '444-4444'],
    (...)
];

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

$contact_rows = [
    0 => ['contact_name' => 'john', 'contact_email' => 'john@gmail.com', 'contact_phone' => '555-5555'],
    1 => ['contact_name' => 'Ed', (...)],
    2 => ['contact_name' => 'Paul', (...)]
];

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:

<input type="text" name="contact[0][name]" value="1">
<input type="text" name="contact[0][email]" value="2">
<input type="text" name="contact[0][phone]" value="3">
<input type="text" name="contact[1][name]" value="4">
<input type="text" name="contact[1][email]" value="5">
<input type="text" name="contact[1][phone]" value="6">

After that – print_r($_POST) and enjoy.

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