I have an array from a csv with a similar structure to this:
$array = array(
array(\'name\', \'age\', \'gender\'),
array(\'Ian\', 24, \'male\'),
a
My solution in 2 aproaches.
Save the array values as serialized representations of the data in a simple DB table.
Save the array values in separate table fields.
Working example:
$array = array(
0 => array ( "name", "age", "gender"),
1 => array ( "Ian", "24", "male"),
2 => array ( "Janice", "21", "female")
);
foreach($array as $key1 => $value1){
foreach($value1 as $key2 => $value2){
// assuming the first element (0) in the array is the header value and the header value is a valid array key
if($key1 > 0){
$items[$key1-1][ $array[0][$key2] ] = $value2;
}
}
}
// 1. store values as serialized representation
foreach ($items as $key => $value) {
$sql = "INSERT INTO datatable SET data = ".mysql_real_escape_string(serialize($value))."";
echo $sql.PHP_EOL;
}
// 2. auto create fields in database and store values
foreach ($array[0] as $key1) {
$sql = "ALTER TABLE forms ADD '".$key1."' TEXT NOT NULL";
echo $sql.PHP_EOL;
}
foreach ($items as $key1 => $value1) {
foreach($value1 as $key2 => $value2){
$sql = "INSERT INTO datatable SET ".$key2." = '".mysql_real_escape_string($value2)."'";
echo $sql.PHP_EOL;
}
}