计算文本文件中每个类别的总和 [英] Calculate the total sum for each category from a text file

查看:88
本文介绍了计算文本文件中每个类别的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那里有一个文本文件,我存储着所有这样的数据:

I have a text file there I store all the data like this:

dept|test-1|365|0
dept|test-2|134|0
expense|test-3|4387|0
expense|test-4|105|0

如何获取该类别内所有交易的每个类别的总和?

How can I get the sum of each category for all the transaction within that category?

在此示例中,类别dept的总和为499,类别expense的总和为4'492.

In this example, the category dept will have a total sum of 499 and the category expense will have a total sum of 4'492.

但是如何在PHP中做到这一点?

But how can I do this within PHP?

这是我当前的代码:

function do_maths($expression) {
    eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
    return $o;
}

function inifile($fname, $word) {
    $contents = file_get_contents($fname.'.ini');
    $pattern = preg_quote($word, '/');
    $pattern = "/^.*$pattern.*\$/m";

    if(preg_match_all($pattern, $contents, $matches)) {
        sort($matches[0]);

        # TABELL
        echo '<div class="table">';

            # LOOP
            foreach($matches[0] AS $found) {
                $transaction = explode('|', $found);

                echo '<div class="table-row'.($transaction[3] == 1 ? ' color-grey-light" title="'.$transaction[1].' är betalad"' : '"').'>';
                    echo '<div class="table-cell-left table-cell-left-width">';
                        echo $transaction[1];
                    echo '</div>';

                    echo '<div class="table-cell-right">';
                        echo '<span class="sum">';
                            echo do_maths($transaction[2]);
                        echo '</span> kr';
                    echo '</div>';
                echo '</div>';
            }

        echo '</div>';


    } else {
        echo '<div class="message color-blue">';
            echo 'Kunde inte hitta något';
        echo '</div>';
    }
}

推荐答案

这应该对您有用:

首先使用 file() 将文本文件读入数组.然后遍历每个数组元素(文本文件的每一行)和 explode() 通过|作为分隔符.

First read your text file into an array with file(). Then go through each array element(each line of your text file) and explode() it by | as delimiter.

所以您的数组将从(第1点的数组)处更改:

So your array will change from (Array at point 1):

Array
(
    [0] => dept|test-1|365|0
    [1] => dept|test-2|134|0
    [2] => expense|test-3|4387|0
    [3] => expense|test-4|105|0
)

到(第2点的数组):

Array
(
    [0] => Array
        (
            [0] => dept
            [1] => test-1
            [2] => 365
            [3] => 0
        )
    //...
)

此后,您可以遍历$lines数组,并使用类别(subArray的第一个数组元素)作为索引,并将值(第三个数组元素)添加到数组中.

After this you can loop through your $lines array and use the category (first array element of the subArray) as index and add the value (third array element) to the array.

然后,您可以为每个类别subArray调用 array_sum() array_map() .

Then you can call array_sum() for each category subArray with array_map().

因此,您将每个类别的所有值加在一起.因此,您的数组(第3点的数组):

So you sum all values together for each category. So your array (Array at point 3):

Array
(
    [dept] => Array
        (
            [0] => 365
            [1] => 134
        )

    [expense] => Array
        (
            [0] => 4387
            [1] => 105
        )

)

会变成这样(第4点的数组):

Will become like this (Array at point 4):

Array
(
    [dept] => 499
    [expense] => 4492
)

最后,只需遍历数组并显示数据:

And at the end just loop through your array and display your data:

<?php

    $lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);  //Array at point 1
    $lines = array_map(function($v){
        return explode("|", $v);
    }, $lines);  //Array at point 2

    foreach($lines as $line)
        $data[$line[0]][] = $line[2];
    //Array at point 3  
    $result = array_map("array_sum", $data); 
    //Array at point 4
    foreach($result as $category => $sum)
        echo $category . " = " . $sum . "<br>";

?>

输出:

dept = 499
expense = 4492

因此我实现到您的函数中的代码将如下所示:

So my code implemented into your function will look something like this:

<?php

    function getCategoryFromFile($fileName, $category) {
        $lines = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        $lines = array_map(function($v){
            return explode("|", $v);
        }, $lines);

        $keys = array_keys(array_column($lines, 0), $category);


        if(!empty($keys)) {

            echo '<div class="table">';

            foreach($keys as $key) {

                echo '<div class="table-row' . ($lines[$key][3] == 1 ? ' color-grey-light" title="' . $lines[$key][1] . ' är betalad"' : '"') . '>';
                    echo '<div class="table-cell-left table-cell-left-width">';
                        echo $lines[$key][1];
                    echo '</div>';                      
                echo '</div>';

            }

            echo '<div class="table-cell-right">';
                echo '<span class="sum">';
                    echo array_sum(array_column(array_intersect_key($lines, array_flip($keys)), 2));
                echo '</span> kr';
            echo '</div>';

            echo '</div>';

        } else {
            echo '<div class="message color-blue">';
                echo 'Kunde inte hitta något';
            echo '</div>';
        }

    }

    //As example
    getCategoryFromFile("test.txt", "expense");

?>

第一部分与我上面的代码相同.但是,现在只遍历所需类别的数据,我们需要这些子数组的键.我们从这行获得的信息:

The first part is the same as in my code above. But to now only loop through the data of the category which you want we need the keys to these subArrays. Which we get with this line:

$keys = array_keys(array_column($lines, 0), $category);

因此,基本上,我们使用array_column($lines, 0)从您的数组中获取所有类别,这将返回如下数组:

So basically we grab all categories from your array with array_column($lines, 0), which will return an array like this:

Array
(
    [0] => dept
    [1] => dept
    [2] => expense
    [3] => expense
)

然后使用 array_keys() $category您想要的类别中该数组的键.例如,expense将是:

Then with array_keys() and $category we only get the keys of this array from the category which you want. Which for example for expense will be:

Array
(
    [0] => 2
    [1] => 3
)

然后,我们只检查是否有一些键,即是否有您想要的类别的行.如果是,我们将遍历这些键并使用它们来访问所需的数据.

Then we just check if we have some keys, means some lines with the category which you want. If yes we loop through these keys and use them to access the data, which you want.

在foreach循环中,打印值的总和后,我们使用以下行:

After the foreach loop to print the sum of the values we use this line:

echo array_sum(array_column(array_intersect_key($lines, array_flip($keys)), 2));

但是让我们将其分解一下.首先我们有:

But let's break it a bit down. First we have:

array_intersect_key($lines, array_flip($keys))

使用 array_intersect_key()来获取这两个数组的关键相交的地方.在左侧,我们将数组$lines作为第一个数组,据我们所知,它看起来像这样:

Where we grab the key intersect of these two arrays with array_intersect_key(). On the left side we have the array $lines as first array which as we know looks something like this:

Array
(
    [0] => Array
        (
            [0] => dept
            [1] => test-1
            [2] => 365
            [3] => 0
        )
    //...
)

现在在另一侧作为第二个数组,我们有了想要的类别中的键,所以:

Now on the other side as second array we have the keys from the category which we want, so:

Array
(
    [0] => 2
    [1] => 3
)

然后结果/相交将是(注意:由于我们抓住了它们键的相交,因此我们必须使用$keys. array-flip.php"rel =" nofollow> array_flip() ):

And then the result/intersect will be (Note: Since we grab the intersect of they keys, we have to flip $keys with array_flip()):

Array
(
    [2] => Array
        (
            [0] => expense
            [1] => test-3
            [2] => 4387
            [3] => 0
        )

    [3] => Array
        (
            [0] => expense
            [1] => test-4
            [2] => 105
            [3] => 0
        )

)

在此数组之外,我们使用 array_column()从每个子数组中获取第二列.因此,从上面的数组中我们将得出:

Out of this array we get the second column from each subArray with array_column(). So from the above array we will end up with:

Array
(
    [0] => 4387
    [1] => 105
)

然后最后我们用array_sum()得到这个数组的和,你将得到:

And then finally we get the sum of this array with array_sum() and you will get:

4492

这篇关于计算文本文件中每个类别的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆