2011-11-23 41 views
0

数组$ALLOWED_CALLS包含一个函数名称和所需的参数。我想筛选$_REQUEST阵列,只需要其中的参数即可获得$params阵列。如何?

$call = 'translate'; 

$ALLOWED_CALLS = array(
    'getLanguages' => array(), 
    'detect' => array('text'), 
    'translateFrom' => array('text', 'from', 'to'), 
    'translate' => array('text', 'to'), 
); 

$params = array(); // Should contain $_REQUEST['text'] and $_REQUEST['to'] 

回答

1

我会使用array_intersect_key()像这样:

$params = array_intersect_key($_REQUEST, array_flip($ALLOWED_CALLS[$call])); 

因此,整个事情:

$call = 'translate'; 

$ALLOWED_CALLS = array(
    'getLanguages' => array(), 
    'detect' => array('text'), 
    'translateFrom' => array('text', 'from', 'to'), 
    'translate' => array('text', 'to'), 
); 

$params = array_intersect_key($_REQUEST, array_flip($ALLOWED_CALLS[$call])); 
+0

优雅的解决方案,谢谢。 – gremo

+0

+1可能还会检查$ call是否存在作为$ ALLOWED_CALLS中的一个键的完整性。 – liquorvicar

+0

@livvvicar当然,不能与此争论。另一件可能需要的是检查“text”和“to”(在这种情况下)都存在于预期的位置。就像这样,这段代码将把它们包含在'$ params'中,如果它们存在于'$ _REQUEST'中,但目前没有确保它们确实存在的地方。 – Wiseguy

0

喜欢的东西:

$contains_required = true; 
foreach($ALLOWED_CALLS[$call] as $key => $value) 
{ 
    if(!in_array($value, $_REQUEST)) 
    { 
     $contains_required = false; 
    } 
} 
0
function getParams ($call, $allowedCalls) { 
    // Return FALSE if the call was invalid 
    if (!isset($allowedCalls[$call])) return FALSE; 
    // Get allowed params from $_REQUEST into result array 
    $result = array(); 
    foreach ($allowedCalls[$call] as $param) { 
    if (isset($_REQUEST[$param])) { 
     $result[$param] = $_REQUEST[$param]; 
    } 
    } 
    // Return the result 
    return $result; 
} 

返回$ params数组或失败时的FALSE

相关问题