php
  • arrays
  • 2013-03-25 3 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()'을 정의합니까? 함수 자체를 수정하지 않으려면 데이터를 배열에 넣고 배열을 반복하고 루프 내에서 함수를 호출하십시오. –

    답변

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

    call_user_func_array()에 대한 더 많은 정보는 PHP 매뉴얼에서 찾을 수 있습니다 : http://php.net/manual/en/function.call-user-func-array.php

    +0

    +1 좋았어, 배열을 반복하고 crear()를 호출하는 다른 함수를 만드는 것이 좋습니다. – Waygood

    +0

    첫 번째 매개 변수로 호출되는 함수의 이름을 추가 할 수 있습니다;) – Crisp

    +0

    @Crisp - heh, yep. :) 좋은 지점. 생각보다 빨리 타이핑하기;) – Spudley

    관련 문제