note 100281 added to function.fgetcsv

From: Date: Tue, 05 Oct 2010 23:30:54 +0000
Subject: note 100281 added to function.fgetcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-172991@lists.php.net to get a copy of this message
If you receive data in the following format: Time,Dataset1,Dataset2, timestamp1,item 1 for dataset 1,item1 for dataset2 timestamp2,item 2 for dataset 1,item2 for dataset2 the following code will output a series of arrays grouped by column with the resulting format: array ( [column 1 title] => array ( [timestamp1] => item1 for dataset1 [timestamp2] => item2 for dataset1 ) [column 2 title] => array ( [timestamp1] => item1 for dataset2 [timestamp2] => item2 for dataset2 ) ) <?php # Open the File. if (($handle = fopen("rawdata.csv", "r")) !== FALSE) { # Set the parent multidimensional array key to 0. $nn = 0; while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { # Count the total keys in the row. $c = count($data); # Populate the multidimensional array. for ($x=0;$x<$c;$x++) { $csvarray[$nn][$x] = $data[$x]; } $nn++; } # Close the File. fclose($handle); } // take the row'ified data and columnize the array function columnizeArray($csvarray) { $array = array(); foreach($csvarray as $key=>$value) { // reparse into useful array data. if ($key == 0) { foreach ($value AS $key2=>$value2) { $array[$key2] = array(); $array[$key2][] = $value2; } }else if ($key > 0){ foreach ($value as $key3=>$value3) { $array[$key3][] = $value3; } }else{ } } return $array; } function groupColumns($array = null) { $array2 = array(); foreach ($array as $k=>$v) { // procss each column // $k = column number // $v = array of rows if ($k == 0) {}else{ // working on column 2 or higher $array2[$v[0]] = array(); foreach ($array[0] as $k1=>$v1) { if ($v1 > 0) { // ignore the column heading // store the first column variable in as the key. // Store the value associated with this item as the value. $array2[$v[0]][$v1] = $v[$k1]; } } } } return $array2; } $array2 = groupColumns(columnizeArray($csvarray)); print_r($array2); ?> ---- Server IP: 208.69.120.55 Probable Submitter: 209.119.212.6 ---- Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php Edit -- https://master.php.net/note/edit/100281 Del: integrated -- https://master.php.net/note/delete/100281/integrated Del: useless -- https://master.php.net/note/delete/100281/useless Del: bad code -- https://master.php.net/note/delete/100281/bad+code Del: spam -- https://master.php.net/note/delete/100281/spam Del: non-english -- https://master.php.net/note/delete/100281/non-english Del: in docs -- https://master.php.net/note/delete/100281/in+docs Del: other reasons-- https://master.php.net/note/delete/100281 Reject -- https://master.php.net/note/reject/100281 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172991) next »