我有一个包含以下行的csv文件
enter code here
23,cars,43 063
23,cars,17 306
23,houses,13 300
23,garage,13 094
23,hotels,10 025
22,cars,75 675
22,cars,40 403
22,houses,32 243
22,garage,30 649
22,hotels,29 734
21,hotels,29 734
22,hotels,29 734
这是我用来解析csv文件的代码
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
当我显示$ line_of_text的内容时;数组,这是我得到的
Array
(
[0] => Array
(
[0] => 23
[1] => cars
[2] => 43 063
)
[1] => Array
(
[0] => 23
[1] => cars
[2] => 17 306
)
[2] => Array
(
[0] => 23
[1] => houses
[2] => 13 300
)
.....
但这不是我想要的,我希望我的阵列以这种方式显示
array (
23 => array(
'cars' => 43063,
'houses' => 17306,
'shops' => 13300,
'garages' => 13094,
'hotels' => 10025
),
22 => array(
'cars' => 75675,
'houses' => 40403,
'shops' => 32243,
'garages' => 30649,
'hotels' => 29734,
'test' => 29734
)
);
我如何实现这一目标?你能帮我吗?
//更新我的新数组的内容
Array
(
[0] => Array
(
[0] => cars
[1] => 00
[2] => 0
)
[1] => Array
(
[0] => cars
[1] => 01
[2] => 0
)
[2] => Array
(
[0] => cars
[1] => 02
[2] => 0
)
[3] => Array
(
[0] => cars
[1] => 11
[2] => 0
)
[4] => Array
(
[0] => cars
[1] => 23
[2] => 4425
)
[5] => Array
(
[0] => houses
[1] => 00
[2] => 198
)
[6] => Array
(
[0] => houses
[1] => 01
[2] => 742
)
[7] => Array
(
[0] => houses
[1] => 02
[2] => 168
)
)
答案 0 :(得分:1)
$fp = fopen($csvFile, 'r');
$master = array();
while( $line = fgetcsv( $fp ) ) {
// 23,cars,43 063
if( !isset( $master[$line[0]] ) )
$master[$line[0]] = array();
if( !isset( $master[$line[0]][$line[1]] ) )
$master[$line[0]][$line[1]] = 0;
$n = filter_var($line[2], FILTER_SANITIZE_NUMBER_INT);
$master[$line[0]][$line[1]] += $n;
}
var_dump( $master );
没有测试,但应该工作。如果您有任何问题,请告诉我。
答案 1 :(得分:1)
尝试这样的事情!
$line_of_text=array();
while (!feof($file_handle) ) {
$line = fgetcsv($file_handle, 1024);
if(isset($line_of_text[ $line[0] ][ $line[1] ] ))
$line_of_text[$line[0]][$line[1]]+=str_replace(" ", "", $line[2]);
else
$line_of_text[$line[0]][$line[1]]=str_replace(" ", "", $line[2]);
}