【发布时间】:2018-10-18 18:43:07
【问题描述】:
我通过导入 CSV 文件获取这些数据。在 CSV 文件中,我的第一列是 Years,所有其他列都是 Make。我正在使用 csvreader 库来解析 CSV 文件中的数据。
我的 CSVReader 库。
class CI_Csvreader {
var $fields; /** columns names retrieved after parsing */
var $separator = ','; /** separator used to explode each line */
/**
* Parse a text containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_text($p_Text) {
$lines = explode("\n", $p_Text);
return $this->parse_lines($lines);
}
/**
* Parse a file containing CSV formatted data.
*
* @access public
* @param string
* @return array
*/
function parse_file($p_Filepath) {
$lines = file($p_Filepath);
return $this->parse_lines($lines);
}
/**
* Parse an array of text lines containing CSV formatted data.
*
* @access public
* @param array
* @return array
*/
function parse_lines($p_CSVLines) {
$content = FALSE;
foreach( $p_CSVLines as $line_num => $line ) {
if( $line != '' ) { // skip empty lines
$elements = explode($this->separator, $line);
if( !is_array($content) ) { // the first line contains fields names
$this->fields = $elements;
$content = array();
} else {
$item = array();
foreach( $this->fields as $id => $field ) {
if( isset($elements[$id]) ) {
$item[$field] = $elements[$id];
}
}
$content[] = $item;
}
}
}
return $content;
}
我的 CSV 文件数据 =>
Years Make Make Make
2001 Acura Honda Toyota
2002 Acura Honda
2003 Acura Toyota
2004
在上述文件中的年份和 Excel/CSV 表中的数据可以稍后更改。
我的输出是一个数组。=>
Array
(
[0] => Array
(
[Years] => 2001
[Make] => Acura
[Make] => Honda
[Make] => Toyota
)
[1] => Array
(
[Years] => 2002
[Make] => Acura
[Make] => Honda
[Make] =>
)
[2] => Array
(
[Years] => 2003
[Make] => Acura
[Make] =>
[Make] => Toyota
)
[3] => Array
(
[Years] => 2004
[Make] =>
[Make] =>
[Make] =>
)
)
我想要这样的结果数组 => 我想保留空值。
Array
(
[0] => Array
(
[Years] => 2001
[Make] => Array(
[0]=>Acura
[1]=>Honda
[2]=>Toyota
)
)
[1] => Array
(
[Years] => 2002
[Make] => Array(
[0]=>Acura
[1]=>Honda
[2]=>
)
)
[2] => Array
(
[Years] => 2003
[Make] => Array(
[0]=>Acura
[1]=>
[2]=>Toyota
)
)
[3] => Array
(
[Years] => 2004
[Make] => Array(
[0]=>
[1]=>
[2]=>
)
)
)
另外请告诉我如何获得没有空值的结果。
如果有任何其他方法可以以我想要的格式从 CSV 文件中获取数据,那也可以。
谁能帮帮我。非常感谢。
【问题讨论】:
标签: php arrays codeigniter key key-value