1

我有以下 json 编码函数来显示 iphone 的推送通知.....但我需要将推送通知消息存储在 DB 中......这样我就可以在使用 php 开发的网站中显示该消息。 ...所以我需要解码这个 json 格式

private function _jsonEncode($array = false)
{
    //Using json_encode if exists
    if (function_exists('json_encode')) {
        return json_encode($array);
    }
    if (is_null($array))
        return 'null';
    if ($array === false)
        return 'false';
    if ($array === true)
        return 'true';
    if (is_scalar($array)) {
        if (is_float($array)) {
            return floatval(str_replace(",", ".", strval($array)));
        }
        if (is_string($array)) {
            static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
            return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $array) . '"';
        } else
            return $array;
    }
    $isList = true;
    for ($i = 0, reset($array); $i < count($array); $i++, next($array)) {
        if (key($array) !== $i) {
            $isList = false;
            break;
        }
    }
    $result = array();
    if ($isList) {
        foreach ($array as $v)
            $result[] = $this->_jsonEncode($v);
        return '[' . join(',', $result) . ']';
    } else {
        foreach ($array as $k => $v)
            $result[] = $this->_jsonEncode($k) . ':' . $this->_jsonEncode($v);
        return '{' . join(',', $result) . '}';
    }
}
4

3 回答 3

1

如果我是你,我会使用标准的 PHP 函数:

json_encode http://php.net/manual/en/function.json-encode.php

json_decode http://php.net/manual/en/function.json-decode.php

于 2013-08-30T12:47:46.157 回答
0

这是因为您的 json 字符串不正确。您应该在“[”之后使用“{”,并且应该在大括号字符串中定义索引。

例如

json_decode('{"aps":{"alert":"mounika4"},"acme2":[{"0":"bang","1":"whiz"}]}');

或者

json_decode('{"aps":{"alert":"mounika4"},"acme2":{"0":"bang","1":"whiz"}}');

你想要的任何数组格式。

于 2013-08-31T13:49:22.487 回答
0

您可以简单地使用 php 的 json_decode() 函数来解码 json 数据。如果 php 提供了相同的内置函数,则无需编写解码 json 的代码。

于 2013-08-30T13:17:19.743 回答