PHP 5.6以下不支持array_column(),需用自定义函数兜底;PHP 5.3不支持json_last_error_msg(),需手动映射错误码;PHP 5.2的mb_strtolower()不支持$encoding参数,应提前设置默认编码。
PHP 5.6 以下不支持 array_column() 怎么办
这个函数在 PHP 5.5 及更早版本根本不存在,直接调用会报 Fatal error: Call to undefined function array_column()。别急着升级环境,先用原生循环兜底。
常见场景是提取二维数组中某字段值(比如从用户列表里取所有 id):
function array_column_fallback($input, $column_key, $index_key = null) {
$result = array();
foreach ($input as $row) {
if (!is_array($row)) continue;
$value = $column_key === null ? $row : $row[$column_key];
if ($index_key !== null && isset($row[$index_key])) {
$result[$row[$index_key]] = $value;
} else {
$result[] = $value;
}
}
return $result;
}
- 注意判断
$row是否为数组,避免Notice: Undefined index - 如果原始数据含非数组项(如
null或字符串),跳过可防崩溃 - 该实现不完全等价于 PHP 7+ 的
array_column()(比如对对象支持弱),但覆盖 95% 的数组提取需求
PHP 5.3 不支持 json_last_error_msg() 怎么获取 JSON 错误信息
PHP 5.4 才引入这个函数,旧版只能靠 json_last_error() 返回码硬查。手动映射比临时升级 PHP 更快。
错误码含义没变,只是没封装成字符串:
立即学习“PHP免费学习笔记(深入)”;