CSV to Associative Array CSV to Associative Array php php

CSV to Associative Array


Too many long solutions. I've always found this to be the simplest:

<?php    /* Map Rows and Loop Through Them */    $rows   = array_map('str_getcsv', file('file.csv'));    $header = array_shift($rows);    $csv    = array();    foreach($rows as $row) {        $csv[] = array_combine($header, $row);    }?>


run over the csv file line by line, and insert to array like:

$array = $fields = array(); $i = 0;$handle = @fopen("file.csv", "r");if ($handle) {    while (($row = fgetcsv($handle, 4096)) !== false) {        if (empty($fields)) {            $fields = $row;            continue;        }        foreach ($row as $k=>$value) {            $array[$i][$fields[$k]] = $value;        }        $i++;    }    if (!feof($handle)) {        echo "Error: unexpected fgets() fail\n";    }    fclose($handle);}


To create an associative list array use something like:

$keys = fgetcsv($f);while (!feof($f)) {    $array[] = array_combine($keys, fgetcsv($f));}

And to traverse and filter by specific attributes write a function like:

function find($find) {    foreach ($array as $row) {         if (array_intersect_assoc($row, $find) == $find) {             $result[] = $row;         }    }}

Where you would invoke it with $find = array(Brand=>Honda, Model=>Civic, Part=>135) to filter out the searched models. The other positional array structure seems not very workable, unless you only want to access the "Test" attribute.