根据另一个数组过滤$ _REQUEST数组?

时间:2011-11-23 14:02:32

标签: php arrays request

数组$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']

4 个答案:

答案 0 :(得分:4)

答案 1 :(得分: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]));

答案 2 :(得分:0)

类似的东西:

$contains_required = true;
foreach( $ALLOWED_CALLS[$call] as $key => $value )
{
    if(!in_array($value, $_REQUEST))
    {
        $contains_required = false;
    }
}

答案 3 :(得分: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