gpt4 book ai didi

php - 在 PHP5.1.6 上运行时获取 json 为 null 输出

转载 作者:行者123 更新时间:2023-12-01 04:54:32 24 4
gpt4 key购买 nike

我正在尝试使用 ajax 和 jquery 从 php 获取二维数组。

问题是,当我在 php5.4.7 中运行它时,我得到了预期的 json 响应

[["A",46],["B",35],["C",68],["D",30],["E",27],["F",85]]

但是对于 php5.1.6,我得到的响应是 json 为 null。我怎样才能让它在PHP5.1.6中工作?

$.ajax({
type: "POST",
url: "get_data.php",
data: "",
dataType: "json",
success: function (json) {
var data = json;

initChart(data);
}
});
<小时/>
header('Content-Type: application/json');

$arr=array();
$arr = array(
array('A', 46),
array('B', 35),
array('C', 68),
array('D', 30),
array('E', 27),
array('F', 85),
);
echo json_encode($arr);

最佳答案

json_encode 需要 版本 > 5.2.0

为了向后兼容,请使用下面的代码

if (!function_exists('json_encode'))
{
function json_encode($a=false)
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a))
{
if (is_float($a))
{
// Always use "." for floats.
return floatval(str_replace(",", ".", strval($a)));
}

if (is_string($a))
{
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
else
return $a;
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a))
{
if (key($a) !== $i)
{
$isList = false;
break;
}
}
$result = array();
if ($isList)
{
foreach ($a as $v) $result[] = json_encode($v);
return '[' . join(',', $result) . ']';
}
else
{
foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
return '{' . join(',', $result) . '}';
}
}
}

关于php - 在 PHP5.1.6 上运行时获取 json 为 null 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15608483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com