代码之家  ›  专栏  ›  技术社区  ›  Gammer

PHP:CSV到数组

  •  -3
  • Gammer  · 技术社区  · 6 年前

    我有以下csv

    CSV formate

    我想把它转换成:

    $data = array(
     'firstName[0]' => 'test1',
     'lastName[0]' => 'test1',
     'email[0]' => 'test1@gmail.com'
     'firstName[1]' => 'test2',
     'lastName[1]' => 'test2',
     'email[1]' => 'test2@gmail.com'
     ...
     ...
    );
    

    $csvData = file_get_contents('filename.csv');
    $lines = explode(PHP_EOL, $csvData);
    $array = array();
    foreach ($lines as $key => $value) {
        $array[$key] = str_getcsv($value);
    }
    

    输出:

    Output

    哪一个在我的情况下是错误的,我如何才能做到这一点?

    0 回复  |  直到 6 年前
        1
  •  2
  •   Future Coder    6 年前

    希望对你有帮助

    public function importCsv()
    {
        $file = public_path('upload/test.csv');
    
        $customerArr = $this->csvToArray($file);
    
        for ($i = 0; $i < count($customerArr); $i ++)
        {
        //   $customerArr[$i];
           //get data and insert or you ca use
        }
    
         print_r($customerArr);
    
    }
    
    
    function csvToArray($filename = '', $delimiter = ',')
    {
        if (!file_exists($filename) || !is_readable($filename))
            return false;
    
        $header = null;
        $data = array();
        if (($handle = fopen($filename, 'r')) !== false)
        {
            while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
            {
                if (!$header)
                    $header = $row;
                else
                    $data[] = array_combine($header, $row);
            }
            fclose($handle);
        }
    
        return $data;
    }
    
        2
  •  0
  •   pr1nc3    6 年前
    <?php
    $csv = array_map('str_getcsv', file('filename.csv'));
    
    for ($j = 1; $j < count($csv); $j++) {
        for ($i = 0; $i < count($csv[0]); $i++) {
            $myArray[$csv[0][$i].$j] = $csv[$j][$i];
        }
    }
    
    print_r($myArray);
    

    不是最优雅的解决方案,但会为你工作。我用过 for

    Array
    (
        [firstName1] => test1
        [lastName1] => Test1
        [email1] => test1@gmail.com
        [firstName2] => test2
        [lastName2] => Test2
        [email2] => test2@gmail.com
    )
    

    我的csv文件是这样的:

    firstName,lastName,email
    test1,Test1,test1@gmail.com
    test2,Test2,test2@gmail.com
    

    嵌套循环将遍历每个嵌套数组,并基于第一个包含头信息的循环连接新的键字段并创建新的数组。

    如果你想要的话 确切地

    <?php
    $csv = array_map('str_getcsv', file('filename.csv'));
    
    for ($j = 1; $j < count($csv); $j++) {
        for ($i = 0; $i < count($csv[0]); $i++) {
            $counter = $j-1;
            $myArray[$csv[0][$i].'['.$counter.']'] = $csv[$j][$i];
        }
    }
    
    print_r($myArray);
    

    它将为您输出一个数组,就像您在问题中要求的那样:

    Array
    (
        [firstName[0]] => test1
        [lastName[0]] => Test1
        [email[0]] => test1@gmail.com
        [firstName[1]] => test2
        [lastName[1]] => Test2
        [email[1]] => test2@gmail.com
    )