note 100155 added to function.json-encode

From: Date: Tue, 28 Sep 2010 18:34:19 +0000
Subject: note 100155 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-172778@lists.php.net to get a copy of this message
I think there are some problems with Dave's json_encode: it assumes the input is an array, does not reset the depth counter for future calls, counts width as well as depth, and does not encode keys. This version seems to be testing ok. Please excuse my cryptic variable names! <?php function ufecru($ip) { /* Recursive utf8_encode BY Ian at booksort INPUT $ip Scalar or array value; array may be associative and/or multidimensional; untested with objects RETURN The input value with all keys and values utf_encoded; if an arbitrary recursion depth has been exceeded the empty string is returned on final exit */ static $dp = 0; // Recursion depth static $dpmx = 512; // Recursion depth limit (as json_decode default) static $fa = false; // Fail flag: true if a whole nest of recursions should fail $rt = ''; // Result if ($fa) goto rr; // Non-essential timesaver - omit if your PHP does not have goto if (is_array($ip)) { if (!$fa = ++ $dp > $dpmx) { // If recursion depth limit exceeded, set fail flag and prevent further recursion foreach($ip as $ipky => $ipva) $rt[(utf8_encode($ipky))] = ufecru($ipva); } $dp --; } else $rt = utf8_encode($ip); rr: // Omit if your PHP does not have goto if ($fa && $dp === 0) { // If fail flag is set and this is the end of the outermost call $fa = false; // Reset for any future user $rt = ''; // Make the entire result empty (without this a faulty partial result may be returned) } return $rt; } ?> Test: <?php $sweet = array('a' => 'apple', 'b' => array('xxx', 'yyy')); $fruits = array('sweet' => $sweet, 'sour' => 'lemon'); $va = ufecru($fruits); echo '<pre>'; print_r(json_decode(json_encode($va), TRUE)); echo '</pre>'; // Gives scalar or array ?> Change $dpmx to 2 to see the result on failure. ---- Server IP: 87.124.126.137 Probable Submitter: 84.92.139.196 (proxied: 84.92.139.196) ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/100155 Del: integrated -- https://master.php.net/note/delete/100155/integrated Del: useless -- https://master.php.net/note/delete/100155/useless Del: bad code -- https://master.php.net/note/delete/100155/bad+code Del: spam -- https://master.php.net/note/delete/100155/spam Del: non-english -- https://master.php.net/note/delete/100155/non-english Del: in docs -- https://master.php.net/note/delete/100155/in+docs Del: other reasons-- https://master.php.net/note/delete/100155 Reject -- https://master.php.net/note/reject/100155 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172778) next »