PHP从csv

时间:2015-09-01 21:03:04

标签: php arrays csv categories

我有一个CSV文件,如下所示:

CategoryA;ID0001;title1
CategoryA;ID0002;title2
CategoryB;ID0001;title3
CategoryB;ID0002;title4
CategoryC;ID0001;title5

[More categories, IDs and titles...]

为了按类别对这些条目进行排序,并且类别中的ID我需要至少2个PHP阵列。第一个带有类别和一个像#34; cat"第二个ID具有类似" id"。

的密钥

我对此的可怕尝试:

function read_csv($filename){
    $rows = array();

    foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line){
        $rows[] = str_getcsv($line, ';');
    };

    return $rows;
};

print_r(read_csv("file.csv"));

看起来像:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => 0001
            [2] => titel1
        )

    [1] => Array
        (
            [0] => A
            [1] => 0002
            [2] => titel2
        )

    [2] => Array
        (
            [0] => B
            [1] => 0001
            [2] => titel3
        )

    [3] => Array
        (
            [0] => B
            [1] => 0002
            [2] => titel4
        )

    [4] => Array
        (
            [0] => C
            [1] => 0001
            [2] => titel5
        )

)

或者有没有办法重命名键?我尝试过的一切都出了问题。我该怎么办?

1 个答案:

答案 0 :(得分:0)

You really need a database, even a simple on like SQLite. But for fun, you can construct the CSV array with column names:

$cols = array('cat', 'id', 'title');

foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line){
    $rows[] = array_combine($cols, str_getcsv($line, ';'));
}

Then you can use array_column() and sort with array_multisort():

array_multisort(array_column($rows, 'cat'),  $rows);

Or maybe:

array_multisort(array_column($rows, 'cat'), array_column($rows, 'id'), $rows);

Without the column names you can still use the numeric index:

array_multisort(array_column($rows, 0), array_column($rows, 1), $rows);