I am reading data from file and displaying array like below code :
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 file data :
005-4410040 |BIRM| 0
005-4410040 |CHI |
450 005-4410040 |CIN | 144
I want total sum of 2nd index of the array it means 320 + 450 + 144
in seperate varriable.
How can i achieve this ? Already tried array_column but its not working.
Update What i have tried :
$sum = array_sum(array_column($row,$row['2']));
You should be able to achieve that using array_column()
and array_sum()
like this
$row = [
['005-4410040','BIRM',1],
['005-4410040','CHI',2],
['005-4410040','CIN',3]
];
$tot = array_sum(array_column($row, 2));
RESULT
6
You are not understanding fgetcsv()
correctly, it gets one line at a time. So each call to fgetcsv return one line from the file which you explode into $row
All you need to do is accumulate $row[2]
as you process over the lines of the file.
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);
}
You are calling wrong sequence
$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)));