簡體   English   中英

如何獲得特定數組索引值的總和

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM