donglu3243 2015-07-09 12:51
浏览 18

使用PHP计算数组中的实例

I'm trying to get a count of how many instances of 'UnitSqFeet' are within a certain range. For example how many instances are between 0 - 175, or 176 - 300.

Here is a part example of the array (it contains 46 in total).

Array ( 
    [0] => Array ( [UnitNumber] => 1.03 [UnitSqFeet] => 60.75 ) 
    [1] => Array ( [UnitNumber] => 1.04 [UnitSqFeet] => 160.39 ) 
    [2] => Array ( [UnitNumber] => 1.05 [UnitSqFeet] => 231.55 ) 
    [3] => Array ( [UnitNumber] => 1.06 [UnitSqFeet] => 280.24 )
)

The 'UnitSqFeet' is a string so I'm assuming it'll have to be converted somewhere in there.

I managed to get this working as below but it would only output this in the first cell of an html table and not the rest. After doing some research on here I understand it's because I was repeating the query for every cell and after the first it had already retrieved all the rows. Not sure if there's a solution whereby I can just reset the query?

$counter = 0;
while ($units = odbc_fetch_array($result)) {
    $num = $units['UnitSqFeet'];
    $float = (float)$num;
    if ($float > 0 && $float < 175) {
        count($float);
        $counter++;
    };  
};
echo $counter;
  • 写回答

2条回答 默认 最新

  • doulin9679 2015-07-09 13:10
    关注

    Try as

    $count = $count2 = 0;
    $result = array();
    foreach(array_column($arr,'UnitSqFeet') as $key => $value){
        if(round($value) <= 170){
            if(!isset($result['0-170'])) $result['0-170'] = $count++;
            $result['0-170'] = $count++;
        }else{
            if(!isset($result['171-300'])) $result['171-300'] = $count2++;
            $result['171-300'] = $count2++;
        }
    }
    print_r($result);
    

    Fiddle

    评论

报告相同问题?

悬赏问题

  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败