php - Create multidimensional array for duplicate ID key value -
i trying read in array values csv , create sub-arrays belong primary key field id. e.g currently, have following array structure & content...
id;number;product
1;k12;product1
2;157/03/2014;product1
2;;product2
2;product1
3;156/03/2014;product2
3;156/03/2014;product3
i have php function:
function csv_to_array($file, $delimiter=';') { if(!file_exists($file) || !is_readable($file)) return false; $header = null; $data = array(); if (($handle = fopen($file, 'r')) !== false) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) { if(!$header) $header = $row; else $data[] = array_combine($header, $row); } fclose($handle); } return $data; }
such result achieve
[1] => array ( [lp] => 1 [number] => k12 [product] => product1 ) [2] => array ( array ( [lp] => 2 [number] => 157/03/2014 [product] => product1 ) array ( [product] => product2 ) array ( [product] => product3 )
replace
data[] = array_combine($header, $row);
with
if(isset($data[$row[0]])) { $data[$row[0]][] = array_combine($header, $row); } else { $data[$row[0]] = array(); $data[$row[0]][] = array_combine($header, $row); }
Comments
Post a Comment