PHP 8.1中array_map与strip_tags搭配出现类型错误的问题排查
问题场景
解析JSON得到嵌套数组结构后,尝试用array_map结合strip_tags清理transactions数据时,触发致命错误:
PHP Fatal error: Uncaught TypeError: strip_tags(): Argument #1 ($string) must be of type string, array given
错误原因
$decoded['transactions']的每个元素是交易子数组,而非字符串。直接对这个数组使用array_map时,回调函数的参数$v是子数组,将数组传入strip_tags违反了PHP 8.1的类型约束,导致报错。
解决方法
针对嵌套数组的层级做处理,以下两种方案任选:
方案1:递归处理所有层级(通用型)
编写递归函数,自动遍历所有嵌套数组,仅对字符串/数字类型的元素执行清理:
function clean_nested_data($value) { if (is_array($value)) { // 递归处理子数组 return array_map('clean_nested_data', $value); } elseif (is_null($value)) { // 保留null,避免后续转0 return null; } else { // 强制转为字符串后清理,兼容数字类型 $cleaned = trim(strip_tags((string)$value)); // 空字符串转回null,适配数据库默认值 return $cleaned === '' ? null : $cleaned; } } // 调用清理transactions数组 $decoded = json_decode($content_raw, true); $decoded['transactions'] = clean_nested_data($decoded['transactions']); // 后续可正常提取变量 extract($decoded['transactions']);
方案2:两层array_map(针对已知层级)
如果确定transactions下只有一层子数组,可直接嵌套array_map处理:
$decoded = json_decode($content_raw, true); $decoded_clean = array_map(function($transaction) { return array_map(function($v) { if (is_null($v)) { return null; } $cleaned = trim(strip_tags((string)$v)); return $cleaned === '' ? null : $cleaned; }, $transaction); }, $decoded['transactions']); extract($decoded_clean);
关键注意点
- PHP 8.1对
strip_tags的参数类型严格校验,必须传入字符串,因此要将数字类型强制转换为字符串后再处理。 - 直接保留
null或把清理后的空字符串转回null,避免数据库将空值默认存为0.000。
内容的提问来源于stack exchange,提问作者TechJunkie
相关产品推荐
相关产品推荐

