Home > database >  Read csv file without a header line and transpose into an indexed array of associative arrays
Read csv file without a header line and transpose into an indexed array of associative arrays

Time:10-19

I'm attempting to create several arrays from a text document.

The text document is formatted as

"1","July 1999"," 2,782,546 "," $17.38 "," $338,545.98 "," 3,004 ",""

"2","August 1999"," 2,739,441 "," $18.68 "," $153,343.98 "," 3,023 ",""

"3","September 1999"," 2,650,431 "," $20.86 "," $308,929.17 "," 3,042 ",""

I need to create several arrays, that combine the date with another field such as:

$Array1 = array("July 1999"=> " 2,782,546 ", "August 1999"=> " 2,739,441 ", "September 1999"=> "2,650,431 ");

$Array2 = array("July 1999"=> " $17.38 ", "August 1999"=> " $18.68 ", "September 1999"=> "$20.86 ");

I can't figure out how to correctly parse the strings to accurately create the arrays.

CodePudding user response:

I was able to parse out the data I needed with this code.

$row = 1;
if (($handle = fopen("file.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row  ;
        for ($c = 1; $c < 2; $c  ) {
            for ($d = 2; $d<3;$d  ){ 
                echo $data[$c] . " " . $data[$d] . "<br />\n" ;
            }
        }
    }
}
fclose($handle);

CodePudding user response:

It's not clear how much flexibility you need (whether the dates / volume of data is dynamic), but you effectively need to parse the csv file lines and transpose the data.

(I'd use fopen() and fgetcsv() as you did, but I could not in the sandbox.)

Code: (Demo)

$csv = <<<TXT
"1","July 1999"," 2,782,546 "," $17.38 "," $338,545.98 "," 3,004 ",""

"2","August 1999"," 2,739,441 "," $18.68 "," $153,343.98 "," 3,023 ",""

"3","September 1999"," 2,650,431 "," $20.86 "," $308,929.17 "," 3,042 ",""
TXT;

$data = [];
// extract the csv data
foreach (
    array_map('str_getcsv', explode("\n\n", $csv))
    as
    $row
) {
    $data[$row[1]] = array_slice($row, 2, -1);
}

$result = [];
// transpose and trim
foreach ($data as $k => $row) {
    foreach ($row as $i => $v) {
        $result[$i][$k] = trim($v);
    }
}
var_export($result);
  • Related