好的,我知道标题可能听起来很混乱,这也是我无法找到答案的原因。
假设我从php
中的mysqli查询得到此表Year| Count
------
1 | 7
2 | 4
3 | 9
并说我知道年份中可能的选项只有1 2或3。
从那个结果我想设置这个代码,但我不确定如何做到最好
$Year1 = 7
$Year2 = 4
$Year3 = 9
答案 0 :(得分:1)
如何使用不同的方法..为什么不根据年份创建索引数组呢?
// perform your sql
$years = array(); // or $years = [];
while ($row = mysqli_fetch_assoc($result)) {
$years[$row['year']] = $row['count'];
}
print_r($years);
这种方法的一些优点......
count($years)
foreach
array_keys($years)
array_values($years)
array_sum($years)
(我喜欢数组)
答案 1 :(得分:0)
while ($row = mysqli_fetch_assoc($result)) {
$Year{$row['year']} = $row['count'];
}
然后,您可以循环记录总数并打印它们
if(!empty($Year1){
echo $Year1;
}
以下是我们在php中使用花括号的方法:
<?php
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>
答案 2 :(得分:0)
假设您可以连接和查询。 我只是这样做,以显示如何使用问题中要求的单个变量。我强烈建议使用@Dale的数组。
$count = 1;
//Define all your variables here
//I set to -1 for checking in the future
//Assuming all counts would be positive.
$Year1 = -1;
$Year2 = -1;
$Year3 = -1;
while ($row = mysqli_fetch_assoc($result)) {
switch($count){
case 1:
$Year1 = $row['count'];
$count++;
break;
case 2:
$Year2 = $row['count'];
$count++;
break;
case 3:
$Year3 = $row['count'];
$count++;
break;
//and so on...you can see this is awful right?
default:
//Something if the case does not exist.
}
}