tags:

views:

70

answers:

3

I have a jQuery function that allows a user to create a list of links. By clicking on an "add row" link they create as many of these blocks (shown below) as they like which they can type the information into.

<div class="links_row">

    <input type="text" name="link_name[]">
    <input type="text" name="link_url[]">

</div>

I am posting this data to a PHP function to insert into a database which looks like this:

+---------------+
|id             |
+---------------+
|name           |
+---------------+
|url            |
+---------------+

I need to work out how to combine the two input arrays link_name[] and link_url[] and loop through the resulting single array, inserting each as a row in the database.

A: 

Combine. You mean like array_merge() combine?

If so, use that.

EDIT: On second thought, you might want array_combine(). It takes two arrays and returns one where one of the input arrays provides the keys and the other provides the values.

Kalium
+1 for array_combine http://br.php.net/manual/en/function.array-combine.php
BrunoLM
how is array_combine going to solve his problem? would love to see a code sample
Ben
array_combine() to associate one array with a second array. Assuming sane HTML, they'll be in the same order. Couple with a table that generates its own IDs (autoincrement or trigger/sequence or whatever) and an inserting foreach.
Kalium
It's a nice function but inserting into a database he will probably just want an array of rows, each being an array of column => value pairs. This is how many frameworks work.
Keyo
We don't even know if there's a framework involved or not. From the way the question was posed, I assumed not.
Kalium
I'm using Codeigniter. I didn't mention that in case it put off people with no knowledge of the framework from answering. I would be interested is hear if this changes things at all?
Plasticated
From your formulation I assumed you were interfacing directly with the database and writing your own queries. There may be a CI-approved way to do this, but I don't know CI.
Kalium
A: 

No, youre better off with an array map because the numbers would correlate. Check out:

http://php.net/manual/en/function.array-map.php

Mike
+1  A: 

Probably not the cleanest way of doing this, but a quick loop should do it. I'm assuming you've validated and sanitized the form data and made sure the arrays are the same size.

$rows = array();

$num_results = count($_POST['link_name']);
for($i = 0; $i < $num_results;  $i++) {
    $rows[$i]['url'] = $_POST['link_url'][$i];
    $rows[$i]['name'] = $_POST['link_name'][$i];
}
Keyo
+1. quick and simple, I think this is more what Plasticated is after
Ben
Thank you, this worked a treat :)
Plasticated