Eddie
Eddie

Reputation: 146

Convert complex array to foreach loop

I have an application where there are 2 initial fields:

  1. Name
  2. Price

the form looks like this:

<form>
<input type="hidden" name="type" value="television" />
<label>Name <input type="text" name="name[]" /></label>
<label>Price <input type="text"" name="price[]" /></label>
</form>

currently a user is able to "add more" fields to the form, which works just fine. So for example if someone clicks on the add more button the form looks like this:

<form>
<input type="hidden" name="type" value="television" />

<label>Name <input type="text" name="name[]" /></label>
<label>Price <input type="text"" name="price[]" /></label>

<label>Name <input type="text" name="name[]" /></label>
<label>Price <input type="text"" name="price[]" /></label>
</form>

And then they can add more names/prices. The problem I'm running into is that I'm not able to associate the first price field with the first name field, and so on and so fourth in when I'm about to insert it into the DB. I'm using ajax to post the data and that's also working just fine.

Currently when I var_dump the post the array looks like this:

array(3) {
  ["type"]=>
  string(10) "television"
  ["name"]=>
  array(2) {
    [0]=>
    string(8) "name one"
    [1]=>
    string(8) "name two"
  }
  ["price"]=>
  array(2) {
    [0]=>
    string(9) "price one"
    [1]=>
    string(9) "price two"
  }
}

What I need is the ability to merge the array values to look exactly like this:

array(
    "name" => "name one",
    "price" => "price one",
    "type" => "television"
)

array(
    "name" => "name two",
    "price" => "price two",
    "type" => "television"
)

Any help would be greatly appreciated!

Upvotes: 0

Views: 510

Answers (1)

Samuel Cook
Samuel Cook

Reputation: 16828

if you know that each name is going to have a price then you could use the key from any of the $_POST array variables to create your output.

Note: this will not create separate arrays but will group the three together for easier "readability":

$_POST = array(
  "type"=> "television",
  "name"=> array("name one","name two"),
  "price"=> array("price one","price two"),
);

$output = array();
foreach($_POST['name'] as $key=>$name){
    $output[$key]['name'] = $name;
    $output[$key]['price'] = $_POST['price'][$key];
    $output[$key]['type'] = $_POST['type'];
}
echo '<pre>',print_r($output),'</pre>';

Upvotes: 2

Related Questions