I would like to ask for help with this task: I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by PHP to Arrays by columns / headers -> for example
$column1 = {123,456}
$column2 = {xyz,zyx}
$column3 = {321,654}
Thanks everyone.
Consider the following code and explanations:
$file = file("example.csv"); // read the file to an array
$cols = array();
for ($i=1;$i<count($file);$i++) { // loop over $file,
// starting in the second line
$row = explode('$', $file[$i]); // make an array with explode
for ($j=0;$j<count($row);$j++) // loop over the $row array
array_push($cols["column".$j], $row[$j]);
// push it to the cols array
}
print_r($cols);
What are your curly brackets supposed to do? In PHP an array is formed with []
.
Rather than reading the whole file to an array you could as well read each line and push it to the cols array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.