我有以下代码:
$limit = (int) $request->input('limit');
$offset = (int) $request->input('offset');
$page = (int) $request->input('page');
$orderBy = (string) $request->input('order_by');
$orderDirection = (string) $request->input('order_direction');
$filters = (string) $request->input('filters');
我想具有系统地分配和转换值的功能。例如:
function castValues($myArray)
{
$urlQueryParams = [];
foreach ($myArray as $value => $type
{
$urlQueryParams[$value] = ($type) $request->input($value);
}
return $urlQueryParams;
}
$params = $this->castValues(['limit' => int, 'offset' => 'int', ...]);
如何将$type
分配为数据类型(int
,string
,...)?
答案 0 :(得分:0)
您可以使用settype
$request = ['limit' => '324', 'offset' => '34'];
function castValues($myArray) {
global $request;
$urlQueryParams = [];
foreach ($myArray as $key => $type) {
settype($request[$key], $type);
$urlQueryParams[$key] = $request[$key];
}
return $urlQueryParams;
}
$params = castValues(['limit' => 'int', 'offset' => 'int']);
var_dump($params);
输出:
array(2) { ["limit"]=> int(324) ["offset"]=> int(34) }