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'],
];
1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

(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 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.

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.