[英]How to get sum of particular Array index values
我正在从文件中读取数据并显示如下代码所示的数组:
if (($fp = fopen("test.txt", "r")) !== FALSE) {
$count = 0;
while(($row = fgetcsv($fp)) !== FALSE)
{
$row = explode("|",$row[0]);
foreach($row as &$el)
{
$el=trim($el);
}
$count++;
$tot = array_sum(array_column($row,2));
echo "<pre>";print_r($row);
if($count>3)
{
break;
}
echo "Coumt :".$tot;
}
echo "Coumt :".$tot;
fclose($fp);
}
Test.txt 文件数据:
005-4410040 |BIRM| 0
005-4410040 |CHI |
450 005-4410040 |CIN | 144
我想要数组的第二个索引的总和,这意味着320 + 450 + 144
在单独的变量中。
我怎样才能做到这一点? 已经尝试过 array_column 但它不起作用。
更新我尝试过的:
$sum = array_sum(array_column($row,$row['2']));
您应该能够像这样使用array_column()
和array_sum()
来实现
$row = [
['005-4410040','BIRM',1],
['005-4410040','CHI',2],
['005-4410040','CIN',3]
];
$tot = array_sum(array_column($row, 2));
结果
6
您没有正确理解fgetcsv()
,它一次只显示一行。 因此,每次调用 fgetcsv 都会从文件中返回一行,然后将其分解为 $row
您需要做的就是在处理文件$row[2]
累积$row[2]
。
if (($fp = fopen("test.txt", "r")) !== FALSE) {
$count = 0;
$tot = 0;
while(($row = fgetcsv($fp)) !== FALSE)
{
$row = explode("|",$row[0]);
$count++;
// I see one line with no value so to be safe
$tot += $row[2] != '' ? $row[2] : 0;
if($count>3) {
break;
}
echo "Coumt : $tot";
}
echo "Coumt : $tot";
fclose($fp);
}
您正在调用错误的序列
$arr=array(array
(
0 => "005-4410040",
1 => "BIRM",
2 => 320
),
array
(
0 => "005-4410040",
1 => "CHI",
2 => 450
),
array
(
0 => "005-4410040",
1 => "CIN",
2 => 144
));
echo (array_sum(array_column($arr, 2)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.