簡體   English   中英

在PHP中從CSV創建多維關聯數組

[英]create multidimensional associative array from CSV in PHP

我正在嘗試在PHP中創建多維數組,其中內部數組與以下示例CSV字符串$ csv相關聯:

# Results from 2015-06-16 to 2015-06-16.
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48

遵循3rd +行格式的實際數據行數是可變的。 到目前為止,我所做的是制作一個普通的多維數組:

$resultArray = str_getcsv($csv, PHP_EOL);//parse the rows
array_shift($resultArray);//shift out results first row: date info
array_shift($resultArray);//shift out results new first row: field labels
foreach($resultArray as &$row) {//parse the items in rows
    $row = str_getcsv($row, ",", '"');//removes the '"' field enclosure?
}//foreach

這構成了一個功能多維數組,但我不知道如何使內部數組具有關聯性,以便可以使用預期使用的數組中的文本友好鍵來訪問它們:

$rowFieldKeysArray = array('date', 'time', 'label', 'artist', 'composer', 'album', 'title', 'duration');

我敢肯定有一種簡單的PHP方法可以將鍵名數組用作關聯數組的鍵,但是我不確定該怎么做。 我寧可懷疑我需要采取以下措施:

foreach($resultArray as $rowKey => &$row) {
    $row[$rowFieldKeysArray[$rowKey]] = str_getcsv($row, ",", '"');
}//foreach

但這會產生“警告:字符串偏移量'date'[...]不合法”。

我該怎么做?

編輯:基於安德魯評論中的鏈接和我接受的答案中提供的組合信息,我能夠使用以下有效代碼解決此問題:

    $resultArray = str_getcsv($csv, PHP_EOL);//parse the rows
    array_shift($resultArray);//shift out results first row: date info
    $rowFieldKeysArray = str_getcsv( array_shift($resultArray), "," );//shift out results new first row: field labels into field key name array
    //array('date', 'time', 'label', 'artist', 'composer', 'album', 'title', 'duration');//array of Key field names for associative array
    //       [0]     [1]      [2]      [3]        [4]        [5]      [6]       [7]      //key index
    foreach($resultArray as &$row) {//parse the items in rows
        $row = array_combine($rowFieldKeysArray, str_getcsv($row, ",", '"'));//array_combine replaces numeric indexes with key field labels
    }//foreach

謝謝!

這可能對您有幫助

腳本-用於csv從文件數組

[akshay@localhost tmp]$ cat test.php
<?php

function csv_to_array($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, 0, $delimiter)) !== FALSE)
        {

            if(!$header)
            {
               $header = $row;
            }
            else
            {
                if(count($header)!=count($row)){ continue; }

                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

print_r(csv_to_array("/tmp/test.csv"));

?>

腳本-用於csv從字符串到數組

[akshay@localhost tmp]$ cat test.php
<?php

function str_to_csv_to_array($string, $delimiter=',')
{
        $header = NULL;
        $data = array();
        $rows = explode(PHP_EOL, $string); 
        foreach($rows as $row_str)
        {
            $row = str_getcsv($row_str);
            if(!$header)
            {
               $header = $row;
            }
            else
            {
                if(count($header)!=count($row)){ continue; }

                $data[] = array_combine($header, $row);
            }
        }

    return $data;
}


$string = <<<EOF
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48
EOF;

print_r(str_to_csv_to_array($string));
?>

輸入文件

[akshay@localhost tmp]$ cat test.csv
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48

兩個腳本都會輸出

[akshay@localhost tmp]$ php test.php
Array
(
    [0] => Array
        (
            [date] => 2015-06-16
            [time] => 12:00 AM
            [label] => Island
            [artist] => U2
            [composer] => Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr
            [album] => Songs Of Innocence
            [title] => SONG FOR SOMEONE
            [duration] => 03:46
        )

    [1] => Array
        (
            [date] => 2015-06-16
            [time] => 12:04 AM
            [label] => Lowden Proud
            [artist] => Fearing & White, Andy White, Stephen Fearing
            [composer] => White- Andy,Fearing- Stephen
            [album] => Tea And Confidences
            [title] => SECRET OF A LONG LASTING LOVE
            [duration] => 03:10
        )

    [2] => Array
        (
            [date] => 2015-06-16
            [time] => 12:07 AM
            [label] => Columbia
            [artist] => The Wallflowers
            [composer] => Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami
            [album] => Glad All Over
            [title] => REBOOT THE MISSION
            [duration] => 03:31
        )

    [3] => Array
        (
            [date] => 2015-06-16
            [time] => 12:10 AM
            [label] => Distort Light
            [artist] => Bend Sinister
            [composer] => Moxon- Daniel
            [album] => Stories Of Brothers, Tales Of Lovers
            [title] => JIMMY BROWN
            [duration] => 03:48
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM