function json_encode($data) { if (is_object($data)) { //对象转换成数组 $data = get_object_vars($data); } else { if (!is_array($data)) { // 普通格式直接输出 return format_json_value($data); } } // 判断是否关联数组 if (empty($data) || is_numeric(implode('', array_keys($data)))) { $assoc = false; } else { $assoc = true; } // 组装 Json字符串 $json = $assoc ? '{' : '['; foreach ($data as $key => $val) { if (!is_null($val)) { if ($assoc) { $json .= "\"{$key}\":" . json_encode($val) . ","; } else { $json .= json_encode($val) . ","; } } } if (strlen($json) > 1) { // 加上判断 防止空数组 $json = substr($json, 0, -1); } $json .= $assoc ? '}' : ']'; return $json; }
function format_json_value($key, $value, $indent) { $formattedText = ''; if (is_array($value) && is_numeric($key)) { $formattedText .= implode(',', $value); } elseif (is_array($value)) { $formattedText .= '<ol>'; foreach ($value as $key2 => $value2) { $formattedText .= "<li>"; if (!is_numeric($key2)) { $formattedText .= "<strong>{$key2}:</strong>"; } $formattedText .= format_json_value($key2, $value2, $indent + 1); $formattedText .= "</li>"; } $formattedText .= "</ol>"; } elseif (is_object($value)) { $formattedText .= '<ul>'; $formattedText .= format_json_object($value, $indent + 1); $formattedText .= "</ul>"; } elseif (is_bool($value)) { if ($value) { $formattedText .= 'True'; } else { $formattedText .= 'False'; } } else { $formattedText .= $value; } return $formattedText; }