如何用递归代码简化冗长嵌套的PHP数组展示函数?
用递归简化PHP数组/对象打印函数darr的方案
当然可以用递归彻底简化这个函数,递归能自动处理任意深度的数组/对象嵌套,无需手动写多层循环,代码量能大幅减少,同时还能保留原函数的所有核心功能:
优化后的递归实现代码
function darr($var, $name = '', $currentPath = '') { static $len = 250; $out = ''; // 初始化顶级变量的标题 if ($name && empty($currentPath)) { $out .= '<b>' . $name . ':</b><br>'; $currentPath = $name; } elseif (empty($currentPath)) { $currentPath = '$' . $name; } // 统一处理数组和对象(将对象转为关联数组) $items = is_object($var) ? get_object_vars($var) : $var; foreach ($items as $key => $value) { $newPath = $currentPath . '[' . $key . ']'; if (is_array($value) || is_object($value)) { // 非空数组/对象才添加标题 if (!empty($value)) { $out .= '<br>' . $newPath . ':<br>'; } // 递归处理子层级 $out .= darr($value, '', $newPath); } else { // 截断过长文本并格式化输出 $displayValue = trim($value, " \n"); if (mb_strlen($displayValue) > $len) { $displayValue = mb_substr($displayValue, 0, $len) . '...'; } $out .= $newPath . ' = ' . $displayValue . '<br>'; } } return $out; }
关键优化点说明
- 递归遍历:用递归替代硬编码的7层循环,支持任意深度的数组/对象嵌套,不会出现原函数中超过7层就无法处理的问题
- 公共逻辑提取:把字符串截断、trim处理等重复逻辑统一提取,避免代码冗余
- 统一数组/对象处理:用
get_object_vars将对象转为关联数组,统一遍历逻辑,无需分开判断 - 路径传递:递归时传递当前变量的完整路径(比如
$data[id][sub]),无需手动拼接多层键名 - 保留原功能:完全保留原函数的HTML格式化、长度限制、变量名标题展示等特性
使用示例
$data = ['id' => 3]; $config = ['last_offer_day' => '01.07.2023']; echo darr($data, '$data'); echo '<br><br>'; echo darr($config, '$config');
输出效果
<b>$data:</b><br> $data[id] = 3<br> <b>$config:</b><br> $config[last_offer_day] = 01.07.2023<br>
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

