[PHP] json类 数组转json json转数组 →→→→→进入此内容的聊天室

来自 , 2021-01-14, 写在 PHP, 查看 155 次.
URL http://www.code666.cn/view/d58e2f07
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4.  * Converts to and from JSON format.
  5.  *
  6.  * JSON (JavaScript Object Notation) is a lightweight data-interchange
  7.  * format. It is easy for humans to read and write. It is easy for machines
  8.  * to parse and generate. It is based on a subset of the JavaScript
  9.  * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  10.  * This feature can also be found in  Python. JSON is a text format that is
  11.  * completely language independent but uses conventions that are familiar
  12.  * to programmers of the C-family of languages, including C, C++, C#, Java,
  13.  * JavaScript, Perl, TCL, and many others. These properties make JSON an
  14.  * ideal data-interchange language.
  15.  *
  16.  * This package provides a simple encoder and decoder for JSON notation. It
  17.  * is intended for use with client-side Javascript applications that make
  18.  * use of HTTPRequest to perform server communication functions - data can
  19.  * be encoded into JSON notation for use in a client-side javascript, or
  20.  * decoded from incoming Javascript requests. JSON format is native to
  21.  * Javascript, and can be directly eval()'ed with no further parsing
  22.  * overhead
  23.  *
  24.  * All strings should be in ASCII or UTF-8 format!
  25.  *
  26.  * LICENSE: Redistribution and use in source and binary forms, with or
  27.  * without modification, are permitted provided that the following
  28.  * conditions are met: Redistributions of source code must retain the
  29.  * above copyright notice, this list of conditions and the following
  30.  * disclaimer. Redistributions in binary form must reproduce the above
  31.  * copyright notice, this list of conditions and the following disclaimer
  32.  * in the documentation and/or other materials provided with the
  33.  * distribution.
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  36.  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  37.  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  38.  * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  39.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  40.  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  41.  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  42.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  43.  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  44.  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  45.  * DAMAGE.
  46.  *
  47.  * @category
  48.  * @package     Services_JSON
  49.  * @author      Michal Migurski <mike-json@teczno.com>
  50.  * @author      Matt Knapp <mdknapp[at]gmail[dot]com>
  51.  * @author      Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  52.  * @copyright   2005 Michal Migurski
  53.  * @version     CVS: $Id: JSON.php 292911 2010-01-02 04:04:10Z alan_k $
  54.  * @license     http://www.opensource.org/licenses/bsd-license.php
  55.  * @link        http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  56.  */
  57.  
  58. /**
  59.  * Marker constant for Services_JSON::decode(), used to flag stack state
  60.  */
  61. define('SERVICES_JSON_SLICE',   1);
  62.  
  63. /**
  64.  * Marker constant for Services_JSON::decode(), used to flag stack state
  65.  */
  66. define('SERVICES_JSON_IN_STR',  2);
  67.  
  68. /**
  69.  * Marker constant for Services_JSON::decode(), used to flag stack state
  70.  */
  71. define('SERVICES_JSON_IN_ARR',  3);
  72.  
  73. /**
  74.  * Marker constant for Services_JSON::decode(), used to flag stack state
  75.  */
  76. define('SERVICES_JSON_IN_OBJ',  4);
  77.  
  78. /**
  79.  * Marker constant for Services_JSON::decode(), used to flag stack state
  80.  */
  81. define('SERVICES_JSON_IN_CMT', 5);
  82.  
  83. /**
  84.  * Behavior switch for Services_JSON::decode()
  85.  */
  86. define('SERVICES_JSON_LOOSE_TYPE', 16);
  87.  
  88. /**
  89.  * Behavior switch for Services_JSON::decode()
  90.  */
  91. define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
  92.  
  93. /**
  94.  * Converts to and from JSON format.
  95.  *
  96.  * Brief example of use:
  97.  *
  98.  * <code>
  99.  * // create a new instance of Services_JSON
  100.  * $json = new Services_JSON();
  101.  *
  102.  * // convert a complexe value to JSON notation, and send it to the browser
  103.  * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
  104.  * $output = $json->encode($value);
  105.  *
  106.  * print($output);
  107.  * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
  108.  *
  109.  * // accept incoming POST data, assumed to be in JSON notation
  110.  * $input = file_get_contents('php://input', 1000000);
  111.  * $value = $json->decode($input);
  112.  * </code>
  113.  */
  114. class Services_JSON
  115. {
  116.    /**
  117.     * constructs a new JSON instance
  118.     *
  119.     * @param    int     $use    object behavior flags; combine with boolean-OR
  120.     *
  121.     *                           possible values:
  122.     *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
  123.     *                                   "{...}" syntax creates associative arrays
  124.     *                                   instead of objects in decode().
  125.     *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
  126.     *                                   Values which can't be encoded (e.g. resources)
  127.     *                                   appear as NULL instead of throwing errors.
  128.     *                                   By default, a deeply-nested resource will
  129.     *                                   bubble up with an error, so all return values
  130.     *                                   from encode() should be checked with isError()
  131.     */
  132.     function Services_JSON($use = 0)
  133.     {
  134.         $this->use = $use;
  135.     }
  136.  
  137.    /**
  138.     * convert a string from one UTF-16 char to one UTF-8 char
  139.     *
  140.     * Normally should be handled by mb_convert_encoding, but
  141.     * provides a slower PHP-only method for installations
  142.     * that lack the multibye string extension.
  143.     *
  144.     * @param    string  $utf16  UTF-16 character
  145.     * @return   string  UTF-8 character
  146.     * @access   private
  147.     */
  148.     function utf162utf8($utf16)
  149.     {
  150.         // oh please oh please oh please oh please oh please
  151.         if(function_exists('mb_convert_encoding')) {
  152.             return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  153.         }
  154.  
  155.         $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
  156.  
  157.         switch(true) {
  158.             case ((0x7F & $bytes) == $bytes):
  159.                 // this case should never be reached, because we are in ASCII range
  160.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  161.                 return chr(0x7F & $bytes);
  162.  
  163.             case (0x07FF & $bytes) == $bytes:
  164.                 // return a 2-byte UTF-8 character
  165.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  166.                 return chr(0xC0 | (($bytes >> 6) & 0x1F))
  167.                      . chr(0x80 | ($bytes & 0x3F));
  168.  
  169.             case (0xFFFF & $bytes) == $bytes:
  170.                 // return a 3-byte UTF-8 character
  171.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  172.                 return chr(0xE0 | (($bytes >> 12) & 0x0F))
  173.                      . chr(0x80 | (($bytes >> 6) & 0x3F))
  174.                      . chr(0x80 | ($bytes & 0x3F));
  175.         }
  176.  
  177.         // ignoring UTF-32 for now, sorry
  178.         return '';
  179.     }
  180.  
  181.    /**
  182.     * convert a string from one UTF-8 char to one UTF-16 char
  183.     *
  184.     * Normally should be handled by mb_convert_encoding, but
  185.     * provides a slower PHP-only method for installations
  186.     * that lack the multibye string extension.
  187.     *
  188.     * @param    string  $utf8   UTF-8 character
  189.     * @return   string  UTF-16 character
  190.     * @access   private
  191.     */
  192.     function utf82utf16($utf8)
  193.     {
  194.         // oh please oh please oh please oh please oh please
  195.         if(function_exists('mb_convert_encoding')) {
  196.             return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  197.         }
  198.  
  199.         switch(strlen($utf8)) {
  200.             case 1:
  201.                 // this case should never be reached, because we are in ASCII range
  202.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  203.                 return $utf8;
  204.  
  205.             case 2:
  206.                 // return a UTF-16 character from a 2-byte UTF-8 char
  207.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  208.                 return chr(0x07 & (ord($utf8{0}) >> 2))
  209.                      . chr((0xC0 & (ord($utf8{0}) << 6))
  210.                          | (0x3F & ord($utf8{1})));
  211.  
  212.             case 3:
  213.                 // return a UTF-16 character from a 3-byte UTF-8 char
  214.                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  215.                 return chr((0xF0 & (ord($utf8{0}) << 4))
  216.                          | (0x0F & (ord($utf8{1}) >> 2)))
  217.                      . chr((0xC0 & (ord($utf8{1}) << 6))
  218.                          | (0x7F & ord($utf8{2})));
  219.         }
  220.  
  221.         // ignoring UTF-32 for now, sorry
  222.         return '';
  223.     }
  224.  
  225.    /**
  226.     * encodes an arbitrary variable into JSON format (and sends JSON Header)
  227.     *
  228.     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
  229.     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
  230.     *                           if var is a strng, note that encode() always expects it
  231.     *                           to be in ASCII or UTF-8 format!
  232.     *
  233.     * @return   mixed   JSON string representation of input var or an error if a problem occurs
  234.     * @access   public
  235.     */
  236.     function encode($var)
  237.     {
  238.         header('Content-type: application/json');
  239.         return $this->encodeUnsafe($var);
  240.     }
  241.     /**
  242.     * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow CSS!!!!)
  243.     *
  244.     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
  245.     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
  246.     *                           if var is a strng, note that encode() always expects it
  247.     *                           to be in ASCII or UTF-8 format!
  248.     *
  249.     * @return   mixed   JSON string representation of input var or an error if a problem occurs
  250.     * @access   public
  251.     */
  252.     function encodeUnsafe($var)
  253.     {
  254.         // see bug #16908 - regarding numeric locale printing
  255.         $lc = setlocale(LC_NUMERIC, 0);
  256.         setlocale(LC_NUMERIC, 'C');
  257.         $ret = $this->_encode($var);
  258.         setlocale(LC_NUMERIC, $lc);
  259.         return $ret;
  260.        
  261.     }
  262.     /**
  263.     * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format
  264.     *
  265.     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
  266.     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
  267.     *                           if var is a strng, note that encode() always expects it
  268.     *                           to be in ASCII or UTF-8 format!
  269.     *
  270.     * @return   mixed   JSON string representation of input var or an error if a problem occurs
  271.     * @access   public
  272.     */
  273.     function _encode($var)
  274.     {
  275.          
  276.         switch (gettype($var)) {
  277.             case 'boolean':
  278.                 return $var ? 'true' : 'false';
  279.  
  280.             case 'NULL':
  281.                 return 'null';
  282.  
  283.             case 'integer':
  284.                 return (int) $var;
  285.  
  286.             case 'double':
  287.             case 'float':
  288.                 return  (float) $var;
  289.  
  290.             case 'string':
  291.                 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  292.                 $ascii = '';
  293.                 $strlen_var = strlen($var);
  294.  
  295.                /*
  296.                 * Iterate over every character in the string,
  297.                 * escaping with a slash or encoding to UTF-8 where necessary
  298.                 */
  299.                 for ($c = 0; $c < $strlen_var; ++$c) {
  300.  
  301.                     $ord_var_c = ord($var{$c});
  302.  
  303.                     switch (true) {
  304.                         case $ord_var_c == 0x08:
  305.                             $ascii .= '\b';
  306.                             break;
  307.                         case $ord_var_c == 0x09:
  308.                             $ascii .= '\t';
  309.                             break;
  310.                         case $ord_var_c == 0x0A:
  311.                             $ascii .= '\n';
  312.                             break;
  313.                         case $ord_var_c == 0x0C:
  314.                             $ascii .= '\f';
  315.                             break;
  316.                         case $ord_var_c == 0x0D:
  317.                             $ascii .= '\r';
  318.                             break;
  319.  
  320.                         case $ord_var_c == 0x22:
  321.                         case $ord_var_c == 0x2F:
  322.                         case $ord_var_c == 0x5C:
  323.                             // double quote, slash, slosh
  324.                             $ascii .= '\\'.$var{$c};
  325.                             break;
  326.  
  327.                         case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  328.                             // characters U-00000000 - U-0000007F (same as ASCII)
  329.                             $ascii .= $var{$c};
  330.                             break;
  331.  
  332.                         case (($ord_var_c & 0xE0) == 0xC0):
  333.                             // characters U-00000080 - U-000007FF, mask 110XXXXX
  334.                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  335.                             if ($c+1 >= $strlen_var) {
  336.                                 $c += 1;
  337.                                 $ascii .= '?';
  338.                                 break;
  339.                             }
  340.                            
  341.                             $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
  342.                             $c += 1;
  343.                             $utf16 = $this->utf82utf16($char);
  344.                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
  345.                             break;
  346.  
  347.                         case (($ord_var_c & 0xF0) == 0xE0):
  348.                             if ($c+2 >= $strlen_var) {
  349.                                 $c += 2;
  350.                                 $ascii .= '?';
  351.                                 break;
  352.                             }
  353.                             // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  354.                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  355.                             $char = pack('C*', $ord_var_c,
  356.                                          @ord($var{$c + 1}),
  357.                                          @ord($var{$c + 2}));
  358.                             $c += 2;
  359.                             $utf16 = $this->utf82utf16($char);
  360.                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
  361.                             break;
  362.  
  363.                         case (($ord_var_c & 0xF8) == 0xF0):
  364.                             if ($c+3 >= $strlen_var) {
  365.                                 $c += 3;
  366.                                 $ascii .= '?';
  367.                                 break;
  368.                             }
  369.                             // characters U-00010000 - U-001FFFFF, mask 11110XXX
  370.                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  371.                             $char = pack('C*', $ord_var_c,
  372.                                          ord($var{$c + 1}),
  373.                                          ord($var{$c + 2}),
  374.                                          ord($var{$c + 3}));
  375.                             $c += 3;
  376.                             $utf16 = $this->utf82utf16($char);
  377.                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
  378.                             break;
  379.  
  380.                         case (($ord_var_c & 0xFC) == 0xF8):
  381.                             // characters U-00200000 - U-03FFFFFF, mask 111110XX
  382.                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  383.                             if ($c+4 >= $strlen_var) {
  384.                                 $c += 4;
  385.                                 $ascii .= '?';
  386.                                 break;
  387.                             }
  388.                             $char = pack('C*', $ord_var_c,
  389.                                          ord($var{$c + 1}),
  390.                                          ord($var{$c + 2}),
  391.                                          ord($var{$c + 3}),
  392.                                          ord($var{$c + 4}));
  393.                             $c += 4;
  394.                             $utf16 = $this->utf82utf16($char);
  395.                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
  396.                             break;
  397.  
  398.                         case (($ord_var_c & 0xFE) == 0xFC):
  399.                         if ($c+5 >= $strlen_var) {
  400.                                 $c += 5;
  401.                                 $ascii .= '?';
  402.                                 break;
  403.                             }
  404.                             // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  405.                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  406.                             $char = pack('C*', $ord_var_c,
  407.                                          ord($var{$c + 1}),
  408.                                          ord($var{$c + 2}),
  409.                                          ord($var{$c + 3}),
  410.                                          ord($var{$c + 4}),
  411.                                          ord($var{$c + 5}));
  412.                             $c += 5;
  413.                             $utf16 = $this->utf82utf16($char);
  414.                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
  415.                             break;
  416.                     }
  417.                 }
  418.                 return  '"'.$ascii.'"';
  419.  
  420.             case 'array':
  421.                /*
  422.                 * As per JSON spec if any array key is not an integer
  423.                 * we must treat the the whole array as an object. We
  424.                 * also try to catch a sparsely populated associative
  425.                 * array with numeric keys here because some JS engines
  426.                 * will create an array with empty indexes up to
  427.                 * max_index which can cause memory issues and because
  428.                 * the keys, which may be relevant, will be remapped
  429.                 * otherwise.
  430.                 *
  431.                 * As per the ECMA and JSON specification an object may
  432.                 * have any string as a property. Unfortunately due to
  433.                 * a hole in the ECMA specification if the key is a
  434.                 * ECMA reserved word or starts with a digit the
  435.                 * parameter is only accessible using ECMAScript's
  436.                 * bracket notation.
  437.                 */
  438.  
  439.                 // treat as a JSON object
  440.                 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  441.                     $properties = array_map(array($this, 'name_value'),
  442.                                             array_keys($var),
  443.                                             array_values($var));
  444.  
  445.                     foreach($properties as $property) {
  446.                         if(Services_JSON::isError($property)) {
  447.                             return $property;
  448.                         }
  449.                     }
  450.  
  451.                     return '{' . join(',', $properties) . '}';
  452.                 }
  453.  
  454.                 // treat it like a regular array
  455.                 $elements = array_map(array($this, '_encode'), $var);
  456.  
  457.                 foreach($elements as $element) {
  458.                     if(Services_JSON::isError($element)) {
  459.                         return $element;
  460.                     }
  461.                 }
  462.  
  463.                 return '[' . join(',', $elements) . ']';
  464.  
  465.             case 'object':
  466.                 $vars = get_object_vars($var);
  467.  
  468.                 $properties = array_map(array($this, 'name_value'),
  469.                                         array_keys($vars),
  470.                                         array_values($vars));
  471.  
  472.                 foreach($properties as $property) {
  473.                     if(Services_JSON::isError($property)) {
  474.                         return $property;
  475.                     }
  476.                 }
  477.  
  478.                 return '{' . join(',', $properties) . '}';
  479.  
  480.             default:
  481.                 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
  482.                     ? 'null'
  483.                     : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
  484.         }
  485.     }
  486.  
  487.    /**
  488.     * array-walking function for use in generating JSON-formatted name-value pairs
  489.     *
  490.     * @param    string  $name   name of key to use
  491.     * @param    mixed   $value  reference to an array element to be encoded
  492.     *
  493.     * @return   string  JSON-formatted name-value pair, like '"name":value'
  494.     * @access   private
  495.     */
  496.     function name_value($name, $value)
  497.     {
  498.         $encoded_value = $this->_encode($value);
  499.  
  500.         if(Services_JSON::isError($encoded_value)) {
  501.             return $encoded_value;
  502.         }
  503.  
  504.         return $this->_encode(strval($name)) . ':' . $encoded_value;
  505.     }
  506.  
  507.    /**
  508.     * reduce a string by removing leading and trailing comments and whitespace
  509.     *
  510.     * @param    $str    string      string value to strip of comments and whitespace
  511.     *
  512.     * @return   string  string value stripped of comments and whitespace
  513.     * @access   private
  514.     */
  515.     function reduce_string($str)
  516.     {
  517.         $str = preg_replace(array(
  518.  
  519.                 // eliminate single line comments in '// ...' form
  520.                 '#^\s*//(.+)$#m',
  521.  
  522.                 // eliminate multi-line comments in '/* ... */' form, at start of string
  523.                 '#^\s*/\*(.+)\*/#Us',
  524.  
  525.                 // eliminate multi-line comments in '/* ... */' form, at end of string
  526.                 '#/\*(.+)\*/\s*$#Us'
  527.  
  528.             ), '', $str);
  529.  
  530.         // eliminate extraneous space
  531.         return trim($str);
  532.     }
  533.  
  534.    /**
  535.     * decodes a JSON string into appropriate variable
  536.     *
  537.     * @param    string  $str    JSON-formatted string
  538.     *
  539.     * @return   mixed   number, boolean, string, array, or object
  540.     *                   corresponding to given JSON input string.
  541.     *                   See argument 1 to Services_JSON() above for object-output behavior.
  542.     *                   Note that decode() always returns strings
  543.     *                   in ASCII or UTF-8 format!
  544.     * @access   public
  545.     */
  546.     function decode($str)
  547.     {
  548.         $str = $this->reduce_string($str);
  549.  
  550.         switch (strtolower($str)) {
  551.             case 'true':
  552.                 return true;
  553.  
  554.             case 'false':
  555.                 return false;
  556.  
  557.             case 'null':
  558.                 return null;
  559.  
  560.             default:
  561.                 $m = array();
  562.  
  563.                 if (is_numeric($str)) {
  564.                     // Lookie-loo, it's a number
  565.  
  566.                     // This would work on its own, but I'm trying to be
  567.                     // good about returning integers where appropriate:
  568.                     // return (float)$str;
  569.  
  570.                     // Return float or int, as appropriate
  571.                     return ((float)$str == (integer)$str)
  572.                         ? (integer)$str
  573.                         : (float)$str;
  574.  
  575.                 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  576.                     // STRINGS RETURNED IN UTF-8 FORMAT
  577.                     $delim = substr($str, 0, 1);
  578.                     $chrs = substr($str, 1, -1);
  579.                     $utf8 = '';
  580.                     $strlen_chrs = strlen($chrs);
  581.  
  582.                     for ($c = 0; $c < $strlen_chrs; ++$c) {
  583.  
  584.                         $substr_chrs_c_2 = substr($chrs, $c, 2);
  585.                         $ord_chrs_c = ord($chrs{$c});
  586.  
  587.                         switch (true) {
  588.                             case $substr_chrs_c_2 == '\b':
  589.                                 $utf8 .= chr(0x08);
  590.                                 ++$c;
  591.                                 break;
  592.                             case $substr_chrs_c_2 == '\t':
  593.                                 $utf8 .= chr(0x09);
  594.                                 ++$c;
  595.                                 break;
  596.                             case $substr_chrs_c_2 == '\n':
  597.                                 $utf8 .= chr(0x0A);
  598.                                 ++$c;
  599.                                 break;
  600.                             case $substr_chrs_c_2 == '\f':
  601.                                 $utf8 .= chr(0x0C);
  602.                                 ++$c;
  603.                                 break;
  604.                             case $substr_chrs_c_2 == '\r':
  605.                                 $utf8 .= chr(0x0D);
  606.                                 ++$c;
  607.                                 break;
  608.  
  609.                             case $substr_chrs_c_2 == '\\"':
  610.                             case $substr_chrs_c_2 == '\\\'':
  611.                             case $substr_chrs_c_2 == '\\\\':
  612.                             case $substr_chrs_c_2 == '\\/':
  613.                                 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  614.                                    ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  615.                                     $utf8 .= $chrs{++$c};
  616.                                 }
  617.                                 break;
  618.  
  619.                             case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  620.                                 // single, escaped unicode character
  621.                                 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
  622.                                        . chr(hexdec(substr($chrs, ($c + 4), 2)));
  623.                                 $utf8 .= $this->utf162utf8($utf16);
  624.                                 $c += 5;
  625.                                 break;
  626.  
  627.                             case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  628.                                 $utf8 .= $chrs{$c};
  629.                                 break;
  630.  
  631.                             case ($ord_chrs_c & 0xE0) == 0xC0:
  632.                                 // characters U-00000080 - U-000007FF, mask 110XXXXX
  633.                                 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  634.                                 $utf8 .= substr($chrs, $c, 2);
  635.                                 ++$c;
  636.                                 break;
  637.  
  638.                             case ($ord_chrs_c & 0xF0) == 0xE0:
  639.                                 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  640.                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  641.                                 $utf8 .= substr($chrs, $c, 3);
  642.                                 $c += 2;
  643.                                 break;
  644.  
  645.                             case ($ord_chrs_c & 0xF8) == 0xF0:
  646.                                 // characters U-00010000 - U-001FFFFF, mask 11110XXX
  647.                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  648.                                 $utf8 .= substr($chrs, $c, 4);
  649.                                 $c += 3;
  650.                                 break;
  651.  
  652.                             case ($ord_chrs_c & 0xFC) == 0xF8:
  653.                                 // characters U-00200000 - U-03FFFFFF, mask 111110XX
  654.                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  655.                                 $utf8 .= substr($chrs, $c, 5);
  656.                                 $c += 4;
  657.                                 break;
  658.  
  659.                             case ($ord_chrs_c & 0xFE) == 0xFC:
  660.                                 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  661.                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  662.                                 $utf8 .= substr($chrs, $c, 6);
  663.                                 $c += 5;
  664.                                 break;
  665.  
  666.                         }
  667.  
  668.                     }
  669.  
  670.                     return $utf8;
  671.  
  672.                 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  673.                     // array, or object notation
  674.  
  675.                     if ($str{0} == '[') {
  676.                         $stk = array(SERVICES_JSON_IN_ARR);
  677.                         $arr = array();
  678.                     } else {
  679.                         if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  680.                             $stk = array(SERVICES_JSON_IN_OBJ);
  681.                             $obj = array();
  682.                         } else {
  683.                             $stk = array(SERVICES_JSON_IN_OBJ);
  684.                             $obj = new stdClass();
  685.                         }
  686.                     }
  687.  
  688.                     array_push($stk, array('what'  => SERVICES_JSON_SLICE,
  689.                                            'where' => 0,
  690.                                            'delim' => false));
  691.  
  692.                     $chrs = substr($str, 1, -1);
  693.                     $chrs = $this->reduce_string($chrs);
  694.  
  695.                     if ($chrs == '') {
  696.                         if (reset($stk) == SERVICES_JSON_IN_ARR) {
  697.                             return $arr;
  698.  
  699.                         } else {
  700.                             return $obj;
  701.  
  702.                         }
  703.                     }
  704.  
  705.                     //print("\nparsing {$chrs}\n");
  706.  
  707.                     $strlen_chrs = strlen($chrs);
  708.  
  709.                     for ($c = 0; $c <= $strlen_chrs; ++$c) {
  710.  
  711.                         $top = end($stk);
  712.                         $substr_chrs_c_2 = substr($chrs, $c, 2);
  713.  
  714.                         if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
  715.                             // found a comma that is not inside a string, array, etc.,
  716.                             // OR we've reached the end of the character list
  717.                             $slice = substr($chrs, $top['where'], ($c - $top['where']));
  718.                             array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
  719.                             //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  720.  
  721.                             if (reset($stk) == SERVICES_JSON_IN_ARR) {
  722.                                 // we are in an array, so just push an element onto the stack
  723.                                 array_push($arr, $this->decode($slice));
  724.  
  725.                             } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  726.                                 // we are in an object, so figure
  727.                                 // out the property name and set an
  728.                                 // element in an associative array,
  729.                                 // for now
  730.                                 $parts = array();
  731.                                
  732.                                 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  733.                                     // "name":value pair
  734.                                     $key = $this->decode($parts[1]);
  735.                                     $val = $this->decode($parts[2]);
  736.  
  737.                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  738.                                         $obj[$key] = $val;
  739.                                     } else {
  740.                                         $obj->$key = $val;
  741.                                     }
  742.                                 } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  743.                                     // name:value pair, where name is unquoted
  744.                                     $key = $parts[1];
  745.                                     $val = $this->decode($parts[2]);
  746.  
  747.                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  748.                                         $obj[$key] = $val;
  749.                                     } else {
  750.                                         $obj->$key = $val;
  751.                                     }
  752.                                 }
  753.  
  754.                             }
  755.  
  756.                         } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
  757.                             // found a quote, and we are not inside a string
  758.                             array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
  759.                             //print("Found start of string at {$c}\n");
  760.  
  761.                         } elseif (($chrs{$c} == $top['delim']) &&
  762.                                  ($top['what'] == SERVICES_JSON_IN_STR) &&
  763.                                  ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
  764.                             // found a quote, we're in a string, and it's not escaped
  765.                             // we know that it's not escaped becase there is _not_ an
  766.                             // odd number of backslashes at the end of the string so far
  767.                             array_pop($stk);
  768.                             //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  769.  
  770.                         } elseif (($chrs{$c} == '[') &&
  771.                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  772.                             // found a left-bracket, and we are in an array, object, or slice
  773.                             array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
  774.                             //print("Found start of array at {$c}\n");
  775.  
  776.                         } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
  777.                             // found a right-bracket, and we're in an array
  778.                             array_pop($stk);
  779.                             //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  780.  
  781.                         } elseif (($chrs{$c} == '{') &&
  782.                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  783.                             // found a left-brace, and we are in an array, object, or slice
  784.                             array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
  785.                             //print("Found start of object at {$c}\n");
  786.  
  787.                         } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
  788.                             // found a right-brace, and we're in an object
  789.                             array_pop($stk);
  790.                             //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  791.  
  792.                         } elseif (($substr_chrs_c_2 == '/*') &&
  793.                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  794.                             // found a comment start, and we are in an array, object, or slice
  795.                             array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
  796.                             $c++;
  797.                             //print("Found start of comment at {$c}\n");
  798.  
  799.                         } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
  800.                             // found a comment end, and we're in one now
  801.                             array_pop($stk);
  802.                             $c++;
  803.  
  804.                             for ($i = $top['where']; $i <= $c; ++$i)
  805.                                 $chrs = substr_replace($chrs, ' ', $i, 1);
  806.  
  807.                             //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  808.  
  809.                         }
  810.  
  811.                     }
  812.  
  813.                     if (reset($stk) == SERVICES_JSON_IN_ARR) {
  814.                         return $arr;
  815.  
  816.                     } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  817.                         return $obj;
  818.  
  819.                     }
  820.  
  821.                 }
  822.         }
  823.     }
  824.  
  825.     /**
  826.      * @todo Ultimately, this should just call PEAR::isError()
  827.      */
  828.     function isError($data, $code = null)
  829.     {
  830.         if (class_exists('pear')) {
  831.             return PEAR::isError($data, $code);
  832.         } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
  833.                                  is_subclass_of($data, 'services_json_error'))) {
  834.             return true;
  835.         }
  836.  
  837.         return false;
  838.     }
  839. }
  840.  
  841. if (class_exists('PEAR_Error')) {
  842.  
  843.     class Services_JSON_Error extends PEAR_Error
  844.     {
  845.         function Services_JSON_Error($message = 'unknown error', $code = null,
  846.                                      $mode = null, $options = null, $userinfo = null)
  847.         {
  848.             parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
  849.         }
  850.     }
  851.  
  852. } else {
  853.  
  854.     /**
  855.      * @todo Ultimately, this class shall be descended from PEAR_Error
  856.      */
  857.     class Services_JSON_Error
  858.     {
  859.         function Services_JSON_Error($message = 'unknown error', $code = null,
  860.                                      $mode = null, $options = null, $userinfo = null)
  861.         {
  862.  
  863.         }
  864.     }
  865.  
  866. }
  867.    
  868.  

回复 "json类 数组转json json转数组"

这儿你可以回复上面这条便签

captcha