0

Content of $csv_content is:

1415797658,456ABC,789,123,"bla"
1415797656,654XYZ,897,567,"foo"
1415797654,639HJW,465,146,"bar"

str_getcsv(file_get_contents($csv_content)) results in:

array
  0 => string '1415797658' (length=10)
  1 => string '456ABC' (length=6)
  2 => string '789' (length=3)
  3 => string '123' (length=3)
  4 => string 'bla' (length=3)
  5 => string '1415797656' (length=10)
  6 => string '654XYZ' (length=6)
  7 => string '897' (length=3)
  8 => string '567' (length=3)
  9 => string 'foo' (length=3)
  10 => string '1415797654' (length=10)
  11 => string '639HJW' (length=6)
  12 => string '465' (length=3)
  13 => string '146' (length=3)
  14 => string 'bar' (length=3)

Desired result:

array
  0 =>
    array
      'timestamp' => string '1415797658' (length=10)
      'id' => string '456ABC' (length=6)
      'id2' => string '789' (length=3)
      'id3' => string '123' (length=3)
      'text' => string 'bla' (length=3)
  1 =>
    array
      'timestamp' => string '1415797656' (length=10)
      'id' => string '654XYZ' (length=6)
      'id2' => string '897' (length=3)
      'id3' => string '567' (length=3)
      'text' => string 'foo' (length=3)
  2 =>
    array
      'timestamp' => string '1415797654' (length=10)
      'id' => string '639HJW' (length=6)
      'id2' => string '465' (length=3)
      'id2' => string '146' (length=3)
      'text' => string 'bar' (length=3)

What would be the neatest way to do this?

5
  • 1
    The examples shown in the docs for PHP's built-in fgetcsv() function might give you a few ideas Commented Nov 12, 2014 at 13:20
  • Your csv should have header. You could expect header, then parse it in first and use first row as keys for the assoc array. After that you parse each row and push new array into another array containing the row with key => value association. Commented Nov 12, 2014 at 13:21
  • @LauriOrgla: CSV is given as it is. Commented Nov 12, 2014 at 13:23
  • 1
    If the CSV doesn't have headers, then you'll need to assign the array keys yourself, but the principle of looping the file using fgetcsv() still applies Commented Nov 12, 2014 at 13:24
  • If you want to be really clever, you use an SplFileObject instead Commented Nov 12, 2014 at 13:25

1 Answer 1

3
$array=array();
$handle=fopen($csv_content,'r');
while ($row=fgetcsv($handle)){
   $array[]=array(
              'timestamp' => $row[0],
              'id' => $row[1],
              'id2' => $row[2],
              'id3' => $row[3],
              'text' => $row[4]
           );
}
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.