![](/img/trans.png)
[英]How to count a specific data/variable in a txt file while comparing it to another txt or csv using PHP?
[英]How to count specific column data in CSV file using PHP
使用fgetcsv()
function 非常簡單
$tot = 0;
if (($f = fopen("filename.csv", "r")) !== FALSE) {
while (($line = fgetcsv($f, 1000, ",")) !== FALSE) {
if ( $line[2] !== '' ) {
$tot += $line[2]; // accumulate column 3
}
}
}
fclose($f);
echo $tot;
$file = fopen('myCSVFile.csv', 'r');
$count = 0;
while (($line = fgetcsv($file)) !== FALSE) {
$num = count($line);
for ($i=0; $i < $num; $i++) {
if(!empty($line[2]) {
$count++;
}
}
}
fclose($file);
echo $count;
您可以使用array_map()
對file()
返回的數組中的每個元素(行)運行回調str_getcsv()
) 。
$arr = array_map('str_getcsv', file('./filename.csv'));
結果( $arr
)看起來像這樣:
Array
(
[0] => Array
(
[0] => First_Name
[1] => Last_name
[2] => Ph_no
)
[1] => Array
(
[0] => ABC
[1] => AB
[2] => 1234567890
)
... etc.
然后,您可以計算電話號碼的數量:
$phNo = array_column($arr, 2);
$phNoCount = count($phNo) -1 ; // subtract the header
echo 'Ph_no count: ' . $phNoCount;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.