note 119215 deleted from function.fgetcsv by cmb

From: Date: Sun, 16 Jun 2019 08:13:34 +0000
Subject: note 119215 deleted from function.fgetcsv by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-211271@lists.php.net to get a copy of this message
Note Submitter: a. s. ---- Method to get table stuckture of CSV as "Columns-Array" and JSON : Tokyo;New York;Berlin 7.0;-2;0.9 6.9;0.8;0.6 9.5;5.7;-3.5 14.5;11.3;8.4 18.2;17.0;13.5 <?php /** * @param string $filename * @param string $delimiter * * @return array|bool */ function csv_to_array($filename = '', $delimiter = ',') { if (!file_exists($filename) || !is_readable($filename)) return false; $header = null; $data = array(); if (($handle = fopen($filename, 'r')) !== false) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) { if (!$header) $header = $row; else { for ($i = 0; $i < sizeof($header); $i++) { $title = $header[$i]; if (!array_key_exists($title, $data)) $data[$title] = ''; if (!is_array($data[$title])) $data[$title] = array(); array_push($data[$title], floatval($row[$i])); } } } fclose($handle); } return $data; } /** * Example */ $data = csv_to_array('data.csv', ';'); print_r($data); echo json_encode($data); ?> Output: Array ( [Tokyo] => Array ( [0] => 7 [1] => 6.9 [2] => 9.5 [3] => 14.5 [4] => 18.2 ) [New York] => Array ( [0] => -2 [1] => 0.8 [2] => 5.7 [3] => 11.3 [4] => 17 ) [Berlin] => Array ( [0] => 0.9 [1] => 0.6 [2] => -3.5 [3] => 8.4 [4] => 13.5 ) ) {"Tokyo":[7,6.9,9.5,14.5,18.2],"New York":[-2,0.8,5.7,11.3,17],"Berlin":[0.9,0.6,-3.5,8.4,13.5]}

« previous php.notes (#211271) next »