第一次预告
foreach (range(1, 70) as $num) {
echo 'Number '.$num.'<br />';
}
第二
ksort($numbers);
foreach ($numbers as $key => $value){
echo 'Number '.$key.' = '.$value.' times<br />';
}
First Foreach从1到70创建数字列表。 Second Foreach从db( $ numbers )中获取一些信息,如
Number 1 = 1 times
Number 2 = 1 times
Number 6 = 1 times
Number 11 = 1 times
Number 12 = 1 times
Number 13 = 1 times
Number 14 = 1 times
Number 16 = 1 times
Number 17 = 1 times
Number 21 = 2 times
Number 24 = 1 times
Number 25 = 1 times
Number 28 = 1 times
Number 30 = 1 times
Number 31 = 2 times
Number 33 = 1 times
Number 36 = 3 times
Number 38 = 1 times
Number 63 = 1 times
Number 65 = 1 times
现在我需要这样做:
if($key==$num){
echo 'Number '.$key.' = '.$value.' times<br />';
}else{
echo 'Number '.$key.' = 0 times<br />';
}
所有这些列表从1到70显示了多少次(如果存在)。感谢
答案 0 :(得分:4)
我会为其创建一个关联数组,数字为键,值为数字。
$numbers = array();
foreach (range(1, 70) as $num)
{
$numbers[$num] = 0;
}
并使用数据库循环将它们组合起来
foreach ($dbnumbers as $num => $value)
{
$numbers[$num] += $value;
}
然后你可以迭代它来显示;)
答案 1 :(得分:2)
对我来说,看起来你正在计算数字的出现次数。
$counter = array();
foreach ($numbers as $num) {
if (!isset($counter[$num]) {
$counter[$num] = 1;
}
else {
$counter[$num]++;
}
}
print_r($counter); # You have all of your occurrences loaded into this tidy array.