Inserting a multi-dimensional php array into a mysql database

前端 未结 8 2002
耶瑟儿~
耶瑟儿~ 2020-12-11 03:36

I have an array from a csv with a similar structure to this:

$array = array(
    array(\'name\', \'age\', \'gender\'),
    array(\'Ian\', 24, \'male\'),
    a         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 03:52

    My solution in 2 aproaches.

    1. Save the array values as serialized representations of the data in a simple DB table.

    2. 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;
        }
    }
    

提交回复
热议问题