'How to create array from a CSV file using PHP
How can I split a csv file into arrays? If the row starts with the letter M I would create a new array and push next lines to it until I had again a row with letter M.
At this moment I push all staff to same array.
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
if($data[0] == 'M'){
$costumerDetail[$x] = $data;
}
else {
$costumerDetail[] = $data;
}
$x++;
}
fclose($handle);
Solution 1:[1]
The main concept is there, using $x to keep track of the array position, but you then go back and just add the next values to the same part level of the array.
This code adds the missing part which is a multidimensional array, so $x is the main thing that keeps track of which set of data you are in and you just add it into that dimension of the array (using [$x][]) till the next M occurs...
$costumerDetail = [[]];
$x = 0;
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
if($data[0] == 'M'){
$x++;
$costumerDetail[$x] = [];
}
$costumerDetail[$x][] = $data;
}
fclose($handle);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nigel Ren |
