ThinkPHP 5.0.24
遇到的问题
当前端POST JSON数据到接口时, JSON中原本的int类型会被转化为string。
举个例子
// 前端传递的数据
{
"id": 30,
"name": "流程1",
"description": "这里是流程1",
"step": 1,
}
// 使用TP框架的获取方法
$this->request->post();
接口接收到的数据直接就转化为string类型了
分析与解决方法
通过查看think/Request源码,我们可以知道:在(当前情况下)调用post()时,$this->post等于解码后的 $content,这个 $content就是 file_get_contents(‘php://input’),即前端提交的数据,所以在这个阶段是没有问题的,问题就在最后的return $this->input()方法。
一看input()方法,其实答案就出来了,直接在post()中加个false就行了,$this->request->post(false);
// think/Request
public function post($name = '', $default = null, $filter = '')
{
if (empty($this->post)) {
$content = $this->input;
if (empty($_POST) && false !== strpos($this->contentType(), 'application/json')) {
$this->post = (array) json_decode($content, true);
} else {
$this->post = $_POST;
}
}
if (is_array($name)) {
$this->param = [];
$this->mergeParam = false;
return $this->post = array_merge($this->post, $name);
}
return $this->input($this->post, $name, $default, $filter);
}
public function input($data = [], $name = '', $default = null, $filter = '')
{
if (false === $name) {
// 获取原始数据
return $data;
}
$name = (string) $name;
if ('' != $name) {
// 解析name
if (strpos($name, '/')) {
list($name, $type) = explode('/', $name);
} else {
$type = 's';
}
// 按.拆分成多维数组进行判断
foreach (explode('.', $name) as $val) {
if (isset($data[$val])) {
$data = $data[$val];
} else {
// 无输入数据,返回默认值
return $default;
}
}
if (is_object($data)) {
return $data;
}
}
// 解析过滤器
$filter = $this->getFilter($filter, $default);
if (is_array($data)) {
array_walk_recursive($data, [$this, 'filterValue'], $filter);
reset($data);
} else {
$this->filterValue($data, $name, $filter);
}
if (isset($type) && $data !== $default) {
// 强制类型转换
$this->typeCast($data, $type);
}
return $data;
}