英文:
Count array elements based on criterias PHP
问题
$array = $result['rawSumSnowDepth'];
foreach ($array as $key => $items) {
if ($items['fSnowDepth'] >= 1 && $items['fSnowDepth'] < 3) {
$value = $items['fMonth'];
$output[$value] = ($output[$value] ?? 0) + 1;
for ($x = 0; $x <= 11; $x++) {
if ($x + 1 == $items['fMonth']) {
$result['snDaysOverAmt'][$x] = array($output[$value]);
} elseif (empty($result['snDaysOverAmt'][$x])) {
$result['snDaysOverAmt'][$x] = array($output[$value] => " ");
}
}
}
}
if (isset($result['snDaysOverAmt'])) {
foreach ($result['snDaysOverAmt'] as $amounts => $amount) {
if ($amount) {
echo '<td>' . implode($amount) . '</td>';
}
}
}
英文:
Looking for help in counting elements in a php array meeting certain criteria and getting them to properly display in html table.
I have this array named $Array
Array
(
[0] => Array
(
[fMonth] => 12
[fSnowDepth] => 0.2
)
[1] => Array
(
[fMonth] => 12
[fSnowDepth] => 3.7
)
[2] => Array
(
[fMonth] => 12
[fSnowDepth] => 1
)
[3] => Array
(
[fMonth] => 01
[fSnowDepth] => 1
)
[4] => Array
(
[fMonth] => 01
[fSnowDepth] => 0.5
)
[5] => Array
(
[fMonth] => 01
[fSnowDepth] => 4.5
)
[6] => Array
(
[fMonth] => 01
[fSnowDepth] => 1.3
)
)
What I'm trying to do is count the months which meet conditions such as fSnowDepth >= 1 and < 3, fSnowDepth >= 3 and < 5, etc. and place in html table. I'm expecting this with (blank) for the months with no count:
| Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
SD >=1 and < 3 | 2 | | | | | | | | | | | 1
SD >=3 and < 5 | 1 | | | | | | | | | | | 1
... etc depths | | | | | | | | | | | |
The code I have is:
$array = $result['rawSumSnowDepth'];
foreach ($array as $key => $items) {
if ($items['fSnowDepth'] >= 1 && $items['fSnowDepth'] < 3) {
$value = $items['fMonth'];
$output[$value] = ($output[$value] ?? 0) + 1;
for ($x = 0; $x <= 11; $x++) {
if ($x + 1 == $items['fMonth']) {
$result['snDaysOverAmt'][$x] = array($output[$value]);
} elseif (empty($result['snDaysOverAmt'][$x])) {
$result['snDaysOverAmt'][$x] = array($output[$value] => "&nbsp;");
}
}
}
}
if (isset($result['snDaysOverAmt'])) {
foreach ($result['snDaysOverAmt'] as $amounts => $amount) {
if ($amount) {
echo '<td>' . implode($amount) . '</td>';
}
}
}
This code works like a charm for the first row of snow depths >= 1 and < 3 but when I run the code again for the next row (>= 3 and < 5) and I get what appears to be a doubling of the first row.
Is there another way to do this so I can include different snow depth counts AND is there a more concise way of doing this? I'm still a PHP rookie so any help would be appreciated.
答案1
得分: -1
$output = [];
$result['snDaysOverAmt'] = [];
这些代码需要放在上述问题中提供的代码的最后一个闭括号之后。
英文:
Thanks to @Barmar this was all that was needed:
$output = [];
$result['snDaysOverAmt'] = [];
these were placed after the last closing bracket in the code provided in the question above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论