Sunday 27 July 2014

Convert CSV to Two dimensional array (2D Array) - PHP 2

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!!!


2 comments: