PHP将csv行拆分为多维数组

时间:2013-10-13 20:45:32

标签: php csv multidimensional-array php-5.4

我正在寻找一种方法将csv行拆分为多维php数组的键

a,b,c成为

$some_array['a']['b']['c'] = true;

a,b,d,e成为

$some_array['a']['b']['d']['e'] = true;

1 个答案:

答案 0 :(得分:4)

也许是这样的?

<?php
$csv_inputstring =
"1,2,3
a,b,c
d,e,f";
$output = array();
foreach(explode("\n",$csv_inputstring) as $line){
   $values = str_getcsv($line);
   $tmp = &$output;
   foreach($values as $value){
      if (!is_array($tmp)){
          $tmp = array();
      }
      $tmp = &$tmp[$value];
   }
   $tmp = true;
}

print_r($output);

?>

此测试的结果:

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => 1
                )

        )

    [a] => Array
        (
            [b] => Array
                (
                    [c] => 1
                )

        )

    [d] => Array
        (
            [e] => Array
                (
                    [f] => 1
                )

        )

)