Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
share|improve this question
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. –  marabutt Oct 13 '13 at 21:13
add comment

1 Answer

up vote 3 down vote accepted

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
                )

        )

)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.