php
  • arrays
  • 2013-03-25 27 views 0 likes 
    0

    假設我有一個像在PHP陣列自動完成同樣的功能

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

    我如何才能讓只有一個調用這個函數傳遞所有這些數據。

    我想做一個數組,但我必須修改函數,什麼是最好的方法... 我可以輕易想到的唯一的一個是奇數和偶數場,其他變量是變量。

    +2

    幾次調用'crear()',但是定義'fill()'?如果你不想修改函數本身,那麼把你的數據放在一個數組中,在數組上循環,然後在循環中調用函數。 – 2013-03-25 16:12:38

    回答

    4

    使用call_user_func_array() function。這使您可以將數組傳遞到通常只接受參數列表的函數中。

    所以我們說你的陣列是這樣的:(基於問題的數據)

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

    您可以在PHP手冊中找到更多關於call_user_func_array()的信息:http://php.net/manual/en/function.call-user-func-array.php

    +0

    +1不錯,我打算建議創建另一個函數來遍歷數組並調用crear(); – Waygood 2013-03-25 16:16:55

    +0

    您可能想要添加被稱爲第一參數的func的名稱;) – Crisp 2013-03-25 16:21:55

    +0

    @Crisp - heh,yep。 :)好點。打字比思考再快;) – Spudley 2013-03-25 16:23:02

    相關問題