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?
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);
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.
精彩评论