I am looking for a way to split a csv line into the keys of a multidimensional php array

a,b,c becomes

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

a,b,d,e becomes

$some_array['a']['b']['d']['e'] = true;
有帮助吗?

解决方案

Maybe something like this?

<?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);

?>

The result for this test:

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

        )

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

        )

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

        )

)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top