我创建了一个CSV,如下所示:
socketEndPoint
然后按照建议编写以下代码:
Name,Title,Salary,Bonus
Bob White,Manager,50000,1000
Mia Sparrow,Programmer,60000,1500
Steven Seagull,Programmer,58000,1400
但不是这个输出:
<?php
$row = 1;
$data = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data[] = fgetcsv($handle)) !== FALSE) {
}
fclose($handle);
}
print_r($data);
?>
我让所有人都在一行:
[0] => Array
(
[0] => Name
[1] => Title
[2] => Salary
[3] => Bonus
)
[1] => Array
(
[0] => Bob White
[1] => Manager
[2] => 50000
[3] => 1000
)
[2] => Array
(
[0] => Mia Sparrow
[1] => Programmer
[2] => 60000
[3] => 1500
)
如何通过键将其拆分为数组,以便我可以使用:
Array ( [0] => Array ( [0] => ��NAME TITLE SALARY BONUS ) [1] => Array ( [0] => BOB MANAGER 50000 1000 ) [2] => Array ( [0] => MIA PROGRAMMER 600001 1500 ) [3] => Array ( [0] => STEVEN PROGRAMMER 58000 1400 ) [4] => Array ( [0] => ) [5] => )
打印我需要的列?
答案 0 :(得分:0)
当您在数组上循环时,只需将与salary
和bonus
对应的列相加,然后在结尾处输出总数。
如果你改变了这个:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
为:
$data = [];
while (($data[] = fgetcsv($handle, 1000, ",")) !== FALSE) {
您最终会在$ data中找到该文件的全部内容,然后您可以对其执行各种array operations。
[编辑]
好的,这就是我在第一部分谈论的内容。让我们说你的.csv文件看起来像这样:
Name,Title,Salary,Bonus
Bob White,Manager,50000,1000
Mia Sparrow,Programmer,60000,1500
Steven Seagull,Programmer,58000,1400
现在,这将为您提供奖金和工资列的总和,并将它们加在一起总计:
const SALARY = 2;
const BONUS = 3;
$salary = 0;
$bonus = 0;
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$salary+= $data[SALARY];
$bonus+= $data[BONUS];
}
fclose($handle);
echo "Totals: ".$salary."+".$bonus." = ".($salary + $bonus);
}
如果要对数据执行其他操作,可以将整个内容存储在数组中,如下所示:
$row = 1;
$data = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data[] = fgetcsv($handle)) !== FALSE) {
}
fclose($handle);
}
现在,print_r($data);
会给你这个:
Array
(
[0] => Array
(
[0] => Name
[1] => Title
[2] => Salary
[3] => Bonus
)
[1] => Array
(
[0] => Bob White
[1] => Manager
[2] => 50000
[3] => 1000
)
[2] => Array
(
[0] => Mia Sparrow
[1] => Programmer
[2] => 60000
[3] => 1500
)
[3] => Array
(
[0] => Steven Seagull
[1] => Programmer
[2] => 58000
[3] => 1250
)
[4] =>
)
和print_r(array_column($data,2));
会给你
Array
(
[0] => Salary
[1] => 50000
[2] => 60000
[3] => 58000
)
这有帮助吗?