0

Lets say I have a text field with the following data. Lines starting with # are comments. The first line is the column headers and values are comma separated.

# some instruction
# some instruction
Day,Open,Close
Monday,09:00,17:00
Tuesday,09:00,18:00

How can I explode this to get an array like this:

$openingTimes = [
   ['Day' => 'Monday', 'Open' => '09:00', 'Close' => '17:00'],
   ['Day' => 'Tuesday', 'Open' => '09:00', 'Close' => '18:00'],
];
adam78
  • 9,668
  • 24
  • 96
  • 207
  • Possible duplicate of [CSV to Json with header row as key](https://stackoverflow.com/questions/10712840/csv-to-json-with-header-row-as-key) – Progrock Feb 15 '19 at 11:41

1 Answers1

3

If you first split the text field by a new line, then process each line one at a time.

Ignore anything starting with a # (the $line[0] == '#' bit).

Use str_getcsv() to split the line into separate fields (allowing for quoted fields etc.) Then if there hasn't been a header so far, then store this split value as the header. If there has been a header, then add this new data as part of the output, combining it with array_combine()...

$input = '# some instruction
# some instruction
Day,Open,Close
Monday,09:00,17:00
Tuesday,09:00,18:00';

$lines = explode(PHP_EOL, $input);
$header = null;
$output = [];
foreach ( $lines as $line ) {
    if ( $line[0] == '#' )  {
        continue;
    }
    $data = str_getcsv($line);
    if ( $header == null )  {
        $header = $data;
    }
    else    {
        $output[] = array_combine($header, $data);
    }
}

print_r($output);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • (I've flagged the question as a dupe. There must be others? This is a nice tidy solution to the given problem. Rather a shame this question doesn't include any workings. This is a 'cookbook' question.) – Progrock Feb 15 '19 at 11:46
  • @Progrock the dupe doesn't deal with commented lines and as it assumes the first line is the header will not work with the sample in OP's question. – Nigel Ren Feb 15 '19 at 15:01