【问题标题】:Calculating average value for array with PHP?用PHP计算数组的平均值?
【发布时间】:2013-12-19 11:45:03
【问题描述】:

我的脑袋都快炸了。我似乎无法创建有效的解决方案。

我有一个这种格式的文件:

99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15

我想为第一列中的每个 id 计算第三列的平均值。

这看起来很简单,但我无法让它工作。您如何从第一列中获得任何所述 id 的平均值?

编辑:

我之前写的一些示例代码:

$file = file_get_contents("results.txt");


$file = explode("
", $file);

$howMany = count($file);

for($a = 0;$a<$howMany;$a++)
{

$row = explode("|", $file[$a]);
$id = $row[0];



$howManyAlready = count($bigTable[$id]);

$bigTable[$id][$howManyAlready] = $row[2];

}

我已经添加了代码。到目前为止,它会将结果放入一个数组中(偏移量与其 id 相对应),但我在如何获取这些结果并计算每个 id 的平均值然后将其呈现在屏幕上时遇到了麻烦。

【问题讨论】:

  • 请提供您已经编写的代码,以及您正在研究的解决方案。并告诉我们您当前的代码有什么问题。
  • 您的值是否已经在数组中,或者在需要读取的单独文件中?
  • 我已经把它全部删除了,因为它让我发疯。我在这个微不足道的问题上坐了 2 个小时。
  • 这些值在一个由新行分隔的 .txt 文件中。
  • @user3010273 Stackoverflow 是关于代码的。编写算法,然后编写一些代码,如果它不起作用,我们将帮助您。以下是一些可能对您有所帮助的函数:fgetcsv 读取文件,array_sumcount 计算每个 id 的平均值。

标签: php arrays sorting average


【解决方案1】:

这样的东西肯定可以工作..

<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
    array_push($arr,@array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);

【讨论】:

    【解决方案2】:

    您可以尝试这样做:

    $file = file_get_contents("results.txt");
    $file = explode("
    ", $file);
    
    $valuesPerID = Array();
    
    foreach($file as $row)
    {
    
        $row_array = explode("|", $row);
    
        $id = $row_array[0];
    
        if(!array_key_exists($id, $valuesPerID))
        {
            $valuesPerID[$id] = Array();
        }
    
        $valuesPerID[$id][] = $row_array[2];
    
    }
    

    现在在 $valuesPerID 数组中,您将拥有所有 ID 作为键,并且对于每个 ID,所有与所述 ID 关联的值。他们可以很容易地计算出这些值的平均值!

    【讨论】:

    • 您应该检查file 函数,它将整个文件读入一个数组,并处理不同的可能行结尾。
    【解决方案3】:

    您可以使用数组映射来分配值和 id。 例如(假设您已经处理了文本):

    <?php
        $data = array("99895|35378|0.01",
            "99895|813|-0.97",
            "99895|771|0.29",
            "442|833|-1.06",
            "442|485|-0.61",
            "442|367|-0.14",
            "442|478|0.77",
            "442|947|-0.07",
            "7977|987|0.76",
            "7977|819|0.37",
            "7977|819|0.36",
            "7977|653|1.16",
            "7977|1653|1.15");
    
        $bucket = array();
        $count = array();
        foreach($data as $line) {
            list($id, $what_s_this, $number) = explode("|", $line);
            $count[$id]++;
            $bucket[$id]+= (float)$number;
        }
    
        foreach($bucket as $id => $sum) {
            echo "id:". $id. ", average". $sum / $count[$id]. "\n";
        }
    

    【讨论】:

    • 刚刚测试过,到处都是未定义的偏移量。
    【解决方案4】:

    这应该会让你走上正轨。

    <?php
    $values = array();
    
    foreach (file('file.txt') as $line) {
        list($id, $thingymabob, $value) = explode('|', $line);
    
        if ( ! array_key_exists($id, $values)) {
            $values[ $id ] = array();
        }
    
        array_push($values[ $id ], $value);
    }
    
    foreach ($values as $id => $value) {
        printf(
            "%d has an average of %f\n",
            $id,
            array_sum($value) / count($value)
        );
    }
    

    【讨论】:

      【解决方案5】:

      这是我刚刚写的一些东西。

      在我的示例中,它从字符串中获取。

      <?php
      $test1 = "";
      $test2 = "";
      $count1 = 0;
      $count2 = 0;
      $string = "99895|35378|0.01
      99895|813|-0.97
      99895|771|0.29
      442|833|-1.06
      442|485|-0.61
      442|367|-0.14
      442|478|0.77
      442|947|-0.07
      7977|987|0.76
      7977|819|0.37
      7977|819|0.36
      7977|653|1.16
      7977|1653|1.15";
      
      $d = explode("\n", $string);
      foreach ($d as $k => $v)
      {
          $d2 = explode("|", $v);
      
          if ($d2[0] == '99895'){
              $count1++;
              $test1 += $d2[2];
          }
          if ($d2[0] == '442'){
              $count2++;
              $test2 += $d2[2];
          }
      }
      
      $result1 = $test1 / $count1;
      $result2 = $test2 / $count2;
      
      echo $result1. " <br> ". $result2;
      

      我不知道这将如何运作,因为我不知道这些值是否已设置。

      【讨论】:

        【解决方案6】:

        如果你尝试下面的代码

        <?php
        $file_content = array();
        $handle = fopen("test.txt", "r");
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                // process the line read.
                $line_ex = explode("|",$line);
                array_push($file_content,$line_ex);
            }
        } else {
            // error opening the file.
        
        }
        
        echo "<pre>";
            print_r($file_content);
            echo "<pre>";
        ?>
        

        然后你会得到下面的输出

        Array
        (
        [0] => Array
            (
                [0] => 99895
                [1] => 35378
                [2] => 0.01
        
            )
        
        [1] => Array
            (
                [0] => 99895
                [1] => 813
                [2] => -0.97
        
            )
        
        [2] => Array
            (
                [0] => 99895
                [1] => 771
                [2] => 0.29
        
            )
        
        [3] => Array
            (
                [0] => 442
                [1] => 833
                [2] => -1.06
        
            )
        
        [4] => Array
            (
                [0] => 442
                [1] => 485
                [2] => -0.61
        
            )
        
        [5] => Array
            (
                [0] => 442
                [1] => 367
                [2] => -0.14
        
            )
        
        [6] => Array
            (
                [0] => 442
                [1] => 478
                [2] => 0.77
        
            )
        
        [7] => Array
            (
                [0] => 442
                [1] => 947
                [2] => -0.07
        
            )
        
        [8] => Array
            (
                [0] => 7977
                [1] => 987
                [2] => 0.76
        
            )
        
        [9] => Array
            (
                [0] => 7977
                [1] => 819
                [2] => 0.37
        
            )
        
        [10] => Array
            (
                [0] => 7977
                [1] => 819
                [2] => 0.36
        
            )
        
        [11] => Array
            (
                [0] => 7977
                [1] => 653
                [2] => 1.16
        
            )
        
        [12] => Array
            (
                [0] => 7977
                [1] => 1653
                [2] => 1.15
            )
        
        )
        

        为了确定相应第一列的第三列的平均值 - 我正在研究它。当我完成时,我会把它放在这里。

        【讨论】:

          【解决方案7】:

          试试这个:

          $filename = 'results.txt';
          $result = $counter = $values = array();
          
          $file = fopen($filename, 'r') or die("Couldn't open $filename");
          while ($line = fgets($file)) {
              $content = explode('|', $line);
              if (empty($content[0]) or empty($content[2]))
                  continue;
          
              $values[$content[0]][] = (float) $content[2];
              ++$counter[$content[0]];
          }
          
          foreach ($values as $key => $value) {
              $result[$key] = array_sum($value) / $counter[$key];
          }
          fclose($file);
          

          【讨论】:

            猜你喜欢
            • 2013-10-25
            • 2014-05-14
            • 1970-01-01
            • 2011-01-03
            • 1970-01-01
            • 2019-04-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多