2
\$\begingroup\$

An optimisation question:

Currently I have entities stored in text files in the following format:

Attribute1,Attribute2,Attribute3
Value1-1,Value1-2,Value1-3
Value2-1,Value2-2,Value2-3
Value3-1,Value3-2,Value3-3

And convert it into a 2D array in the following format:

$array = array(array('Attribute1' => 'Value1-1',
                     'Attribute2', => 'Value1-2',
                     'Attribute3', => 'Value1-3'),
               array('Attribute1' => 'Value2-1',
                     'Attribute2', => 'Value2-2',
                     'Attribute3', => 'Value2-3'),
               array('Attribute1' => 'Value3-1',
                     'Attribute2', => 'Value3-2',
                     'Attribute3', => 'Value3-3'));

Using the following PHP code:

$lines = array();
$dump = normaliseNewLine($dump);
$dump = explode("\n", $dump);
$attributes = explode(',', array_shift($dump));

for($i = 0; $i < count($dump); $i++) {
    $tmp = explode(',', $dump[$i]);
    for ($j = 0; $j < count($tmp); $j++) {
        $lines[$i][$attributes[$j]] = $tmp[$j];
    }
}

I was wondering if there was a more efficient method of completing this task?

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

PHP provides functions to parse CSV files and strings line-by-line.

$file = ...
$headers = fgetcsv($file);
$lines = array();
while (($line = fgetcsv($file)) !== false) {
    $lines[] = array_combine($headers, $line);
}
\$\endgroup\$
1
\$\begingroup\$

This version uses fewer lines, and is slightly quicker for me:

function($fileName)
{
    $handle = fopen($fileName, 'r');
    $attributes = fgetcsv($handle);
    for($i = 0; $line = fgetcsv($handle); $i++)
    {
        foreach($attributes as $k => $attribute)
        {
            $lines[$i][$attribute] = $line[$k];
        }
    }
    return $lines;
}
\$\endgroup\$
2
  • \$\begingroup\$ Just noticed that this code does not produce the correct output! \$\endgroup\$ Apr 11, 2014 at 5:34
  • \$\begingroup\$ @mulquin You're right- updated the answer. \$\endgroup\$
    – MrLore
    Apr 11, 2014 at 14:32

Your Answer

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

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