Convert CSV to Two dimensional array (2D Array) - PHP andrey воскресенье, 27 июля 2014 г. No Comment

When you get the data from CSV file, It will return return array of each row. To work with this, we need to convert it as 2D array. So, this following code snippet will help you to covert CSV array to 2D array. In this we used PHP's array_combine function.

FUNCTION DEFENITION
function get2DArrayFromCsv($file, $delimiter) {
if (($handle = fopen($file, "r+")) !== FALSE) {
$i = 0;
$data2DArray = array();
while (($lineArray = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$data2DArray[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $data2DArray;
}

HOW IT WORKS

* Just used incremental variable $i to mention number of row in 2D array.
* Once finished the iteration for a row, then increment $i for the next row.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
get2DArrayFromCsv($file_path, ',');
Recommended Article : Convert CSV to JSON with header row as key - PHP

Have any doubt? Feel free to comment here!!!


When you get the data from CSV file, It will return return array of each row. To work with this, we need to convert it as 2D array. So, this following code snippet will help you to covert CSV array to 2D array. In this we used PHP's array_combine function.

FUNCTION DEFENITION
function get2DArrayFromCsv($file, $delimiter) {
if (($handle = fopen($file, "r+")) !== FALSE) {
$i = 0;
$data2DArray = array();
while (($lineArray = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$data2DArray[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $data2DArray;
}

HOW IT WORKS

* Just used incremental variable $i to mention number of row in 2D array.
* Once finished the iteration for a row, then increment $i for the next row.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
get2DArrayFromCsv($file_path, ',');
Recommended Article : Convert CSV to JSON with header row as key - PHP

Have any doubt? Feel free to comment here!!!


by Jillur Rahman

Jillur Rahman is a Web designers. He enjoys to make blogger templates. He always try to make modern and 3D looking Templates. You can by his templates from Themeforest.

Follow him @ Twitter | Facebook | Google Plus

No Comment