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.

3 Answers 3

2

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1. quick and simple, I think this is more what Plasticated is after
1

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.

6 Comments

how is array_combine going to solve his problem? would love to see a code sample
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.
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.
We don't even know if there's a framework involved or not. From the way the question was posed, I assumed not.
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?
|
0

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

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

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.