php将表中的数据读取到数组中,并使用条件进行检查


c - php-read data from table into array and check with condition

我有一个程序,它可以检测单列中三分之二的温度数据何时出现,并从中生成错误消息。然而,这个程序是用C编写的,我发现将C与php集成起来很困难。所以我想直接将编码转换为php,但问题是我不知道如何将表中的数据作为数组读取到php中,并根据设计条件进行检查,就像我在下面的C中编程一样:

while (fscanf(fpt, "%f", &t) == 1)  // read until there are no more samples
{
total = 0;   // clear our counter
samples[2] = samples[1];   // toss out the old 3rd sample
samples[1] = samples[0];   // and shift them to make room for the
samples[0] = t;            // one we just read
for(i = 0; i<3; i++)
    if(samples[i] > 180)        // if any are over 180
        total++;                // increment our counter
if(total == 2) {                // if 2 of the 3 are over 180, we got 2 out of 3
    printf("2 out of 3 samples are greater than 180!'n");
    printf("1: %f'n2: %f'n3:%f'n", samples[2],samples[1],samples[0]); //this can be change to echo"..."
    break;
}

}

现在我遇到的问题是while循环,php如何像在C程序中那样将数据读取到数组中。谢谢你的每一次帮助。

PHP非常适合那些不关心性能的懒人。因此,对于大多数libc函数,核心中将有一个PHP包装函数-http://www.php.net/manual/en/function.fscanf.php.您的程序将几乎1比1转换为PHP,所需的只是输入源上的fopen()(从php://stdin视情况而定):

<?php
  $samples = [0,0,0];
  $t = "";
  $fpt = fopen( "php://stdin", "r" ) or die ( "Failed open." );
  while (fscanf($fpt, "%f", $t) == 1)  // read until there are no more $samples
  {
    $total = 0;   // clear our counter
    $samples[2] = $samples[1];   // toss out the old 3rd sample
    $samples[1] = $samples[0];   // and shift them to make room for the
    $samples[0] = $t;            // one we just read
    for($i = 0; $i<3; $i++)
        if($samples[$i] > 180)        // if any are over 180
            $total++;                // increment our counter
    if($total == 2) {                // if 2 of the 3 are over 180, we got 2 out of 3
        printf("2 out of 3 samples are greater than 180!'n");
        printf("1: %f'n2: %f'n3:%f'n", $samples[2],$samples[1],$samples[0]); //this can be change to echo"..."
        break;
    }
  }
?>

假设这个脚本被称为fscanf.php.Test,如下所示:

echo -e "12.0'n.34.5'n.190.45'n450.45'n345.34" | php fscanf.php