dongziya9863 2013-03-25 16:10
浏览 26
已采纳

在php中使用数组自动执行相同的功能

suppose I have a function like

function crear($first, $second, $third, $fourth, $fifth, $sixth){
    $sixth= ($sixth > 0 ? "<span class='required'>*</span>" : "");
    if($fourth=='input'){
        echo "\t   <div class='field-box ".$third."' id='".$first."_field_box'>  
";
        echo "\t\t <div class='display-as-box' id='".$first."_display_as_box'>".$second."  ".$sixth.":</div>  
";
        echo "\t\t <div class='input-box' id='".$first."_input_box'> 
";
        echo "\t\t <input id='field-".$first."' name='".$first."' type='text' maxlength='".$fifth."' /> </div><div class='clear'></div>  
";
        echo "\t   </div>
";
    }
}

And I am calling it several times:

crear('title1', 'Title 1','odd',  'input', '50', 0 );
crear('title2', 'Title 2','even', 'input', '50', 0 );
crear('title3', 'Title 3','odd',  'input', '30', 1 );
crear('title4', 'Title 4','even', 'input', '50', 0 );
crear('title5', 'Title 5','odd',  'select', '19', 1 );
crear('title6', 'Title 6','even', 'select', '19', 0 );

How could I make only one call to this function passing all this data.

I was thinking to make an array but I woul have to modify the function, What would be the best way... The only one I easily can suppose is odd and even field, the others got to be variables.

  • 写回答

1条回答 默认 最新

  • doushan5245 2013-03-25 16:15
    关注

    Use the call_user_func_array() function. This allows you to pass an array into a function that would normally accept just a list of parameters.

    So let's say your array looks like this: (based on the data in the question)

    $input = array(
        array('title1', 'Title 1','odd',  'input', '50', 0 ),
        array('title2', 'Title 2','even', 'input', '50', 0 ),
        array('title3', 'Title 3','odd',  'input', '30', 1 ),
        array('title4', 'Title 4','even', 'input', '50', 0 ),
        array('title5', 'Title 5','odd',  'select', '19', 1 ),
        array('title6', 'Title 6','even', 'select', '19', 0 ),
    );
    

    you can use call_user_func_array() to pass the data into your function like this:

    foreach($input as $data) {
        call_user_func_array('crear', $data);
    }
    

    You can find out more about call_user_func_array() in the PHP manual: http://php.net/manual/en/function.call-user-func-array.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了