note 94157 added to function.json-encode

From: Date: Tue, 20 Oct 2009 09:18:47 +0000
Subject: note 94157 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-161894@lists.php.net to get a copy of this message
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential. e.g.: <?php $myarray = Array('isa', 'dalawa', 'tatlo'); var_dump($myarray); /* output array(3) { [0]=> string(3) "isa" [1]=> string(6) "dalawa" [2]=> string(5) "tatlo" } */ ?> As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array. <?php $myarray = Array('isa', 'dalawa', 'tatlo'); unset($myarray[1]); var_dump($myarray); /* output array(2) { [0]=> string(3) "isa" [2]=> string(5) "tatlo" } */ ?> Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such. SOLUTION: Use array_values() to re-index the array. ---- Server IP: 69.147.83.197 Probable Submitter: 58.71.34.137 ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/94157 Del: integrated -- https://master.php.net/note/delete/94157/integrated Del: useless -- https://master.php.net/note/delete/94157/useless Del: bad code -- https://master.php.net/note/delete/94157/bad+code Del: spam -- https://master.php.net/note/delete/94157/spam Del: non-english -- https://master.php.net/note/delete/94157/non-english Del: in docs -- https://master.php.net/note/delete/94157/in+docs Del: other reasons-- https://master.php.net/note/delete/94157 Reject -- https://master.php.net/note/reject/94157 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#161894) next »