Bryan Seeds

21Apr/110

PHP : csv string to associative array

Here is a handy function :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function CsvStr2Array($str = ''){
$data = array();
$a = str_getcsv($str, "\n");
foreach($a as $k => $v){
if($k == 0){
$columns = str_getcsv($v);
} else {
if($k > 0){
$v = preg_replace("/[^[:print:]]+/", "", $v);
$row = str_getcsv($v);
foreach($columns as $i => $col){
if(is_null($row[$i])){
continue;
}
$data[$k-1][$col] = $row[$i];
}
}
}
}
return $data;
}

might be the most efficient regarding big O notation.. but.. it works =)

VN:F [1.9.10_1130]
Rating: 5.7/6 (3 votes cast)