Home » Structures » Structures_DataGrid_DataSource_CSV » Bug #8252
Allow head line in CSV to produce nice associative array
Details
| Request #8252 | Allow head line in CSV to produce nice associative array |
|---|---|
| Submitted | 2006-07-19 20:32 UTC |
| From | gramlich at eosc dot de |
| Assigned | wiesemann |
| Status | Closed |
| Package | Structures_DataGrid_DataSource_CSV |
| PHP Version | 4.3.2 |
| Roadmaps | (Not assigned) |
Comments
[2006-07-19 20:32 UTC] gramlich at eosc dot de
Description:
------------
It would be nice to have column names, i.e. string indices of an associative array, instead of numeric indices.
I think it's not so unusual for CSV files to contain column names in the first line.
The following patch handles this nicely, if you set the parameter $options = array('headline' => true) for the bind() method. This solution is BC.
--- CSV.phpBAK 2006-07-19 12:08:27.127070240 +0200
+++ CSV.php 2006-07-19 12:33:09.843663056 +0200
@@ -63,10 +63,30 @@
$rowList = explode("\n", $csv);
}
+ if (!empty($this->_options['headline'])) {
+ $keys = explode($this->_options['delimiter'], rtrim($rowList[0]));
+ unset($rowList[0]);
+ } else {
+ $keys = 0;
+ }
+
foreach ($rowList as $row) {
$row = rtrim($row); // to remove DOSish \r
if (!empty($row)) {
- $this->_ar[] = explode($this->_options['delimiter'], $row);
+ if (empty($keys)) {
+ $this->_ar[] = explode($this->_options['delimiter'], $row);
+ } else {
+ $rowAssoc = array();
+ $rowArray = explode($this->_options['delimiter'], $row);
+ foreach ($rowArray as $index => $val) {
+ if (!empty($keys[$index])) {
+ $rowAssoc[$keys[$index]] = $val;
+ } else {
+ $rowAssoc[$index] = $val;
+ }
+ }
+ $this->_ar[] = $rowAssoc;
+ }
}
}