1

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;
Nick Maroulis
  • 486
  • 9
  • 28
  • 1
    What happens if you have a,b,c,d followed by a,b,c? You will first set `$some_array['a']['b']['c']['d'] = true;` which means `$some_array['a']['b']['c']` is an array. But then you will set `$some_array['a']['b']['c']` to be boolean true - overwriting the contents of the first line. You will need to make sure all rows in your CSV have a fixed number of columns for your question to make sense. – Annabel Oct 13 '13 at 21:06
  • @Annabel good point. In this case the data is ordered so that this wont be an issue. – Nick Maroulis Oct 13 '13 at 21:13

1 Answers1

4

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
                )

        )

)
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56