0

I am creating an array from several text boxes. I am needing to move the elements in the array to insert into the database. Here is the array:

array(2) { [0]=> string(7) "nameone" [1]=> string(7) "nametwo" } 
array(2) { [0]=> string(6) "ageone" [1]=> string(6) "agetwo" } 
array(2) { [0]=> string(13) "parentnameone" [1]=> string(13) "parentnametwo" } 
array(2) { [0]=> string(14) "parentemailone" [1]=> string(14) "parentemailtwo" } 
array(2) { [0]=> string(14) "parentphoneone" [1]=> string(14) "parentphonetwo" } 

I want to end up with an insert statement such as:

nameone, ageone, parentnameone, parentemailone, parentphoneone

and next row to insert would be

nametwo, agetwo, parentnametwo, parentemailtwo, parentphonetwo

I have tried to create an array with multiple for each loops but I end up with an array that i need to move the keys which brings be back to my original problem. Is there a method to this madnaess?

Matthew Colley
  • 10,816
  • 9
  • 43
  • 63
  • Which DB, you might be able to bind those as parameters. – user7116 Jun 18 '12 at 15:24
  • @matthewcolley: a better way would be to leave the data alone and use `bind_params` perhaps like this http://stackoverflow.com/questions/2232877/mysqli-bind-params-for-an-insert-query – user7116 Jun 18 '12 at 21:02

3 Answers3

1

Well, lets say your main array contains 5 arrays with 2 elements each. Lets call that $mainArr. "2" in the first line is no. of elements in each subarray. or if the subarraays are not of equal lengths, then the its the length of the largest subarray.

for($i=0;$i<2;$i++) {
foreach($mainArr as $key => $a) {
    $ins[$i][] = $a[$i];
} // form an array with insert elements
}

// traverse that to form inserts
foreach($ins as $key => $arr) {
      $statements[] = implode(",", $ins[$key]);
}

echo '<pre>';
print_r($statements);

I think thats what you want. If not, let me know. Hope that helps!

Ayush Chaudhary
  • 716
  • 1
  • 8
  • 20
0
$l = count($array[0]);
for ($i=0; $i<$l; $i++) {
    // access values like this:
    $name = $array[0][$i]; // equals nameone first time and nametwo second time
    $age = $array[1][$i];
    $parentname = $array[2][$i];
    $parentemail = $array[3][$i];
    $parentphone = $array[3][$i];

    // insert into DB here
}
Jeroen
  • 13,056
  • 4
  • 42
  • 63
-1
#!/usr/bin/php                                                                  
<?php
  $val = array('name', 'age', 'parentname', 'parentemail');
  $key = array('one', 'two', 'three', 'four', 'five');

  $valone = array();
  foreach ($val as $k)
    array_push($valone, $k.$key[0]);

  var_dump($valone);

 ?>

Outputs :

  array(4) {
    [0]=>
    string(7) "nameone"
    [1]=>
    string(6) "ageone"
    [2]=>
    string(13) "parentnameone"
    [3]=>
    string(14) "parentemailone"
  }

Is this what you want you to do ?

togh_j
  • 46
  • 5