0

私が次のような機能を持っているとしましょう

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'>  \n";
        echo "\t\t <div class='display-as-box' id='".$first."_display_as_box'>".$second."  ".$sixth.":</div>  \n";
        echo "\t\t <div class='input-box' id='".$first."_input_box'> \n";
        echo "\t\t <input id='field-".$first."' name='".$first."' type='text' maxlength='".$fifth."' /> </div><div class='clear'></div>  \n";
        echo "\t   </div>\n";
    }
}

そして、私はそれを数回呼んでいます:

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 );

この関数を1回だけ呼び出して、このすべてのデータを渡すにはどうすればよいでしょうか。

配列を作成しようと考えていましたが、関数を変更する必要があります。最善の方法は何でしょうか...簡単に推測できるのは、奇数と偶数のフィールドだけで、他は変数になります。

4

1 に答える 1

4

call_user_func_array()関数を使用します。これにより、通常はパラメータのリストのみを受け入れる関数に配列を渡すことができます。

したがって、配列が次のようになっているとしましょう:(質問のデータに基づく)

$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 ),
);

call_user_func_array()次のように、関数にデータを渡すために使用できます。

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

詳細についてcall_user_func_array()は、PHPマニュアルを参照してください:http://php.net/manual/en/function.call-user-func-array.php

于 2013-03-25T16:15:16.287 に答える