0

I'm posting data from a form with multiple fields. One form needs to send several rows to mySQL, ie.

Row1 -> Field1 Field2 Field3 Field4
Row2 -> Field1 Field2 Field3 Field4
etc...

I've created an array of arrays in the following format:

Array (
[0] => Array (
     [0] => Field1
     [1] => Field1 )
[1] => Array (
     [0] => Field2
     [1] => Field2 )
)

I can't figure out how to reorder them so I can loop through and insert them into my database. I need them to be

Array (
[0] => Array (
     [0] => Field1
     [1] => Field2 )
[1] => Array (
     [0] => Field1
     [1] => Field2 )
)

What's the best way to do this?

2
  • 1
    If you're posting data from your form, why are you not posting the data in the correct format right from the beginning? Commented Jun 12, 2011 at 17:13
  • The form has a variable number of rows, so there may be 1 set of fields posted or there may be 10 sets posted. Commented Jun 12, 2011 at 17:15

2 Answers 2

1

Basically, it's like flipping the matrix 90 degrees (sorry, don't know the proper term). I could not find any built-in function, so here it is -- this will work with ANY number of rows & columns (test data included).

<?php
// input data
$arr = array(
    array('field1-1', 'field1-2'),
    array('field2-1', 'field2-2'),
    array('field3-1', 'field3-2'),
    array('field4-1', 'field4-2'),
);

// some basic validations on input data
if (empty($arr) OR (!isset($arr[0])) OR (empty($arr[0])))
    die('empty or invalid source array');
// almost ready
$result = array();
$rowCount = count($arr[0]);
$fieldsCount = count($arr);
// go go go
for ($r = 0; $r < $rowCount; $r++)
{
    $row = array();
    for ($n = 0; $n < $fieldsCount; $n++)
    {
        $row[] = $arr[$n][$r];
    }
    $result[] = $row;
}

// results are in $result
print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly! I've been working on this one for hours haha!!
0

He's a possible solution for you. This one assume that both of the rows contain the exact same amount of key/value pairs and that each one is in the same order.

foreach ( $row1 as $key => $value )
  $data[$key] = array($row1[$key], $row2[$key]);

Where $row1 is the array contains all of the data that goes in the first row and $row2 is the array that contains all of the data for the second row.

Once the foreach is done, your data should be re-ordered properly in the $data array.

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.