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;
2
  • 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. Commented Oct 13, 2013 at 21:06
  • @Annabel good point. In this case the data is ordered so that this wont be an issue. Commented Oct 13, 2013 at 21:13

1 Answer 1

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
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.