|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2015-11-18 18:23 UTC] nhojohl at gmail dot com
[2015-11-19 02:57 UTC] laruence@php.net
-Status: Open
+Status: Not a bug
[2015-11-19 02:57 UTC] laruence@php.net
[2015-11-19 08:15 UTC] David dot Gausmann at measX dot com
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 16:00:01 2025 UTC |
Description: ------------ I am using php to transfer arrays via JSON. After using natsort/natcasesort for sorting the resulting data aren't JSON arrays anymore. This happens because natsort/natcasesort are changing the datatype of the array keys from int to string (but only when the data becomes sorted; otherwise the key data type won't change). A workaround is it to use usort with strnatcmp/strnatcasecmp as second parameter. Test script: --------------- <?php $array = array('b', 'a', 'c'); echo "After creation:<br>\r\n", json_encode($array), "<br>\r\n"; $array = array('b', 'a', 'c'); sort($array); echo "After sort:<br>\r\n", json_encode($array), "<br>\r\n"; $array = array('b', 'a', 'c'); rsort($array); echo "After rsort:<br>\r\n", json_encode($array), "<br>\r\n"; $array = array('b', 'a', 'c'); natsort($array); echo "After natsort:<br>\r\n", json_encode($array), "<br>\r\n"; $array = array('b', 'a', 'c'); natcasesort($array); echo "After natcasesort:<br>\r\n", json_encode($array), "<br>\r\n"; $array = array('b', 'a', 'c'); usort($array, 'strnatcmp'); echo "After usort(strnatcmp):<br>\r\n", json_encode($array), "<br>\r\n"; ?> Expected result: ---------------- In all used sort functions the result should be an array like ["a","b","c"]. Actual result: -------------- Instead natsort/natcasesort return {"1":"a","0":"b","2":"c"} in JSON syntax. Only the other sort functions return an array like ["a","b","c"].