我应该如何在这种情况下创建全局函数php?

时间:2016-07-31 18:58:51

标签: php html

我有if()代码会很长,其中一些代码会共享一些常见的html代码。我认为更好的方法是根据if条件调用每个html问题。看看我的代码,例如。如果$fruit='apple',我想回应html代码问题1,3,5。我该如何为问题制定全局函数?

<?php
    if($fruit=='apple'){
     /*call question 1,3,5*/
    }else if($fruit=='banana'){
     /*call question 1,2,4*/
    }/*.........a lot of else if.....*/

   /*question
    1. <div>Is it good?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>
    2. <div>where is it from?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>
    3. <div>...........</div>
        .............some multiple choice here
       <input type="text" value="submit"/>
    4. <div>..........</div>
       .............some multiple choice here
       <input type="text" value="submit"/>
    */

?>

2 个答案:

答案 0 :(得分:1)

您可以像这样编写代码:

renderLoading

当然还有其他方法可以做到。您可以构建一个数据结构,为您提供所需的所有信息,包括HTML,然后只需一个小循环即可输出所选的HTML:

$fruit = "apple";

if (in_array($fruit, ["apple", "banana"])) {
    echo '<div>Is it good?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>';
}
if (in_array($fruit, ["banana", "pineapple"])) {
    echo '<div>where is it from?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>';
}
// etc...

答案 1 :(得分:1)

将选项整理成数组

$questions = [
         'q1' => '<div>Is it good?</div>
                 .............some multiple choice here
                 <input type="text" value="submit"/>',
         'q2' => '<div>where is it from?</div>
                 .............some multiple choice here
                 <input type="text" value="submit"/>',
       ];

$fruit_questions = [
         'apple'  => [1,3,5],
         'banana' => [1,2,4],
         'guava' => [17,21,4],
       ];

然后,当您需要提问时,只需:

$question_keys = $fruit_questions[$fruit];

$html_of_questions = ''; // This will hold the questions to echo
foreach($question_keys as $question_key){
    $html_of_questions .= $questions['q'.$question_key]
}

echo $html_of_questions;