给接口方返回数据的时候,经常被要求只返回需要的字段,于是自己写了两个方法分别用于过滤获取结果集中的不需要的字段,使用的过程中需要先定义一个过滤的key数组,然后调用对应的方法处理即可。
过滤单个结果集:
function filterResult(array &$result, array &$filter_key) {
if (!$result) {
return false;
}
$result = array_intersect_key($result, $filter_key);
foreach ($filter_key as $key => $value) {
if (is_array($value) && $value && !empty($result[$key])) {
if (count($result[$key]) != count($result[$key], 1)) {
if (is_numeric(key($value))) {
$result[$key] = array_column($result[$key], reset($value));
} else {
foreach ($result[$key] as &$_value) {
$_value = array_intersect_key($_value, $value);
}
}
} else {
$result[$key] = array_intersect_key($result[$key], $value);
}
}
}
}
过滤结果集数组:
function filterResultList(array &$result_list, array &$filter_key) {
if (!$result_list) {
return false;
}
foreach ($result_list as $key => &$result) {
filterResult($result, $filter_key);
}
}
例如返回的结果如下,这个结果比较粗糙:
{
"total": 1,
"per_page": "10",
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 1,
"data": [
{
"id": 9,
"rule_id": 1,
"sell_uid": 10001,
"seller_id": 1,
"serial_number_prefix": 10,
"serial_number": 10000009,
"cash_code": "fu35m9",
"used": 0,
"used_time": 0,
"order_code": "",
"ctime": "0",
"utime": "0",
"in_time": "0"
}
],
"errcode": 0,
"msg": "操作成功"
}
通过方法处理:
$filter_key = ['total' => '', 'data' => ['id' => '', 'serial_number' => '']];
filterResult($result, $filter_key);
得到的结果就比较简洁了,如下:
{
"total": 1,
"data": [
{
"id": 9,
"serial_number": 10000009
}
],
"errcode": 0,
"msg": "操作成功"
}