减少代码的替代方法

时间:2016-09-02 09:28:27

标签: javascript php

我需要一些帮助,有没有办法减少我的代码?出现此问题尤其是当我使用相当长的数组时,我想知道是否有办法让它们更短?感谢。

$query = "SELECT question,answer FROM easy_ques;";
    $retval = $conn->query($query);

     while($row = $retval->fetch_assoc()) {
            $quest[] = $row['question'];
            $ans[] = $row['answer'];
        }

        echo "<script>";

        echo "var answer = ['$ans[0]','$ans[1]','$ans[2]','$ans[3]','$ans[4]','$ans[5]','$ans[6]','$ans[7]','$ans[8]','$ans[9]','$ans[10]','$ans[11]','$ans[12]','$ans[13]','$ans[14]','$ans[15]','$ans[16]','$ans[17]','$ans[18]','$ans[19]','$ans[20]','$ans[21]','$ans[22]','$ans[23]','$ans[24]','$ans[25]','$ans[26]','$ans[27]','$ans[28]','$ans[29]','$ans[30]','$ans[31]','$ans[32]','$ans[33]','$ans[34]'];";

        echo "var question = ['$quest[0]','$quest[1]','$quest[2]','$quest[3]','$quest[4]','$quest[5]','$quest[6]','$quest[7]','$quest[8]','$quest[9]','$quest[10]','$quest[11]','$quest[12]','$quest[13]','$quest[14]','$quest[15]','$quest[16]','$quest[17]','$quest[18]','$quest[19]','$quest[20]','$quest[21]','$quest[22]','$quest[23]','$quest[24]','$quest[25]','$quest[26]','$quest[27]','$quest[28]','$quest[29]','$quest[30]','$quest[31]','$quest[32]','$quest[33]','$quest[34]'];";

        echo"</script>";

4 个答案:

答案 0 :(得分:1)

这个怎么样?它不依赖于长度并产生可读代码。

$query = "SELECT question,answer FROM easy_ques;";
$retval = $conn->query($query);

echo "<script>\n";

echo "var answer = new Array();\n";
echo "var question = new Array();\n";

while($row = $retval->fetch_assoc())
{
     echo "answer.push('{$row['answer']}');\n";
     echo "question.push('{$row['question']}');\n";
}

echo"</script>";

答案 1 :(得分:1)

您也可以尝试这种方法:

$row = $retval->fetch_assoc();

$questions = "'" . $row['question'] . "'";
$answers = "'" . $row['answer'] . "'";

 while($row = $retval->fetch_assoc()) {
        $questions = $questions . ",'" . $row['question'] . "'";
        $answers = $answers . ",'" . $row['answer'] . "'";
 }

 echo "<script>";

 echo "var answer = [$answers];";

 echo "var question = [$questions];";

 echo "</script>";

答案 2 :(得分:0)

它将是:

0_.;"""0";"0"_0 makes any negative number 0

答案 3 :(得分:0)

您可以使用此方法。将35替换为变量的长度(ans / quests)

RecyclerView