我正在尝试学习一些PHP编码并开始创建自己的小项目。 但是我的代码非常大,当我完成这部分的编码时它会更大,我真的想学习如何使这个更小,也许你们可以帮助我。
以下是它的内容。
获取数据库连接并收到所需信息。
$sql = "SELECT * FROM Users, Achievements WHERE USER_ID = 0 AND ACHIEVEMENT_ID = 0";
$result = $conn->query($sql);
$conn->close();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
foreach($row AS $key => $value)
{
$$key = trim($value);
}
}} else {
echo "0 results";
}
$conn->close();
我创建了一些变量并开始创建一个数组我将完成此操作,但我认为这部分可以更小。
$achievement1 = array("Bench press","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached.");
$achievement2 = array("Deadlift","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached.");
$achievement3 = 'Dipping';
$achievement4 = 'Squats';
$achievement5 = 'Total';
现在最重要的部分我想要了解更多关于值被检查的部分以及将给出回声的部分是bigg,还有3个部分将添加到它下面但是这可能会更小我猜。
if ($ACHIEVEMENT_1 <= 49) {
echo "Youre weak.";
} else if (($ACHIEVEMENT_1 > 49) && ($ACHIEVEMENT_1 < 60)) {
echo $achievement1[1];
} else if (($ACHIEVEMENT_1 > 59) && ($ACHIEVEMENT_1 < 80)) {
echo $achievement1[2];
} else if (($ACHIEVEMENT_1 > 79) && ($ACHIEVEMENT_1 < 100)) {
echo $achievement1[3];
} else if ($ACHIEVEMENT_1 > 99) {
echo $achievement1[4];
}
if ($ACHIEVEMENT_2 <= 49) {
echo "Youre weak.";
} else if (($ACHIEVEMENT_2 > 49) && ($ACHIEVEMENT_2 < 60)) {
echo $achievement2[1];
} else if (($ACHIEVEMENT_2 > 59) && ($ACHIEVEMENT_2 < 80)) {
echo $achievement2[2];
} else if (($ACHIEVEMENT_2 > 79) && ($ACHIEVEMENT_2 < 100)) {
echo $achievement2[3];
} else if ($ACHIEVEMENT_2 > 99) {
echo $achievement2[4];
}
希望你们能够与我一起缩短这段代码。
编辑我已经改变了
<?php
$achievement = array
(
array("Bench press","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached."),
array("Deadlift","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached."),
array("Dipping","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reachxed."),
array("Squats","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached."),
array("Total","50 kilo reached.","60 kilo reached.","80 kilo reached.","100 kilo reached."),
);
for ($row = 0; $row < 5; $row++) {
echo "<p><b>Achievement: ". $achievement[$row][0] ."</b></p>";
echo "<ul>";
for ($col = 1; $col < 4; $col++) {
echo "<li>".$achievement[$row][$col]."</li>";
}
echo "</ul>";
}
?>
但是我需要添加的值,但还是无法弄明白。
答案 0 :(得分:0)
您可以缩短此代码段:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
/* USER NAME */
$USERNAME = $row["USER_NAME"];
/* BENCH PRESS */
$ACHIEVEMENT_1 = $row["ACHIEVEMENT_1"];
/* DEAD LIFT */
$ACHIEVEMENT_2 = $row["ACHIEVEMENT_2"];
/* DIPPING */
$ACHIEVEMENT_3 = $row["ACHIEVEMENT_3"];
/* SQUATS */
$ACHIEVEMENT_4 = $row["ACHIEVEMENT_4"];
/* TOTAL */
$ACHIEVEMENT_5 = $row["ACHIEVEMENT_5"];
}}
以这种方式写作:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
foreach($row AS $key => $value)
{
$$key = trim($value);
}
}}