从csv到多维数组(php)

时间:2016-08-24 15:49:05

标签: php arrays csv

我想从:

A,A,A,A
A,A,A,B
A,A,B,A
A,A,B,B
A,B,A,A
A,B,A,B
A,B,B,A
A,B,B,B
B,A,A,A
B,A,A,B
B,A,B,A
B,A,B,B
B,B,A,A
B,B,A,B
B,B,B,A
B,B,B,B

到:

Array (
[A] => Array
    (
    [A] => Array
        (
        [A] => Array
            (
            [A] => A,
            [B] => B
        [B] => Array
            (
            [A] => A,
            [B] => B
    [B] => Array
        (
        [A] => Array
            (
            [A] => A,
            [B] => B
        [B] => Array
            (
            [A] => A,
            [B] => B
[B] => Array
    (
    [A] => Array
        (
        [A] => Array
            (
            [A] => A,
            [B] => B
        [B] => Array
            (
            [A] => A,
            [B] => B
    [B] => Array
        (
        [A] => Array
            (
            [A] => A,
            [B] => B
        [B] => Array
            (
            [A] => A,
            [B] => B

2 个答案:

答案 0 :(得分:1)

我可能会后悔,但我很无聊。假设你有一个CSV文件,如果没有,那么explode()上的\n CSV字符串或其他:

$lines = file('/path/to/csv.txt');

$array = array();

foreach($lines as $line) {
    $temp  = &$array;

    $path  = str_getcsv($line);
    $value = array_pop($path);

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    $temp[$value] = $value;
}

print_r($array);

答案 1 :(得分:1)

您可以通过拆分换行符将字符串转换为行数组。

然后遍历行并用逗号分隔。您想要的多维数组将通过使用CSV行中的每个值作为结果中较低级别的键来实现。

foreach (explode("\n", $csv_str) as $row) {
    $row = explode(',', $row);
    $result[$row[0]][$row[1]][$row[2]][$row[3]] = $row[3];
}