3
The method asort()
is used to sort arrays, without losing the index.
I sort both the SQL search and the array. However, when sending the data via JSON (using json_encode
), he rearranges the keys.
Example of Array, ordered, mounted with cities and my index in the table:
Array
(
[4550] => AGUA BRANCA
[8339] => ANADIA
[3292] => ARAPIRACA
[7509] => ATALAIA
[21265] => BARRA DE SANTO ANTONIO
[9109] => BARRA DE SAO MIGUEL
...
Example of JSON, shown in browser PREVIEW (still sorted):
"cidades":{"4550":"AGUA BRANCA","8339":"ANADIA","3292":"ARAPIRACA","7509":"ATALAIA","21265":"BARRA DE SANTO ANTONIO","9109":"BARRA DE SAO MIGUEL","6127"
Example of Options, generated via ajax, data:
<option value="314">MACEIO</option>
<option value="872">PILAR</option>
<option value="1145">UNIAO DOS PALMARES</option>
<option value="1432">RIO LARGO</option>
<option value="1647">MARIBONDO</option>
<option value="1648">SAO MIGUEL DOS CAMPOS</option>
<option value="1845">PARIPUEIRA</option>
At the reception of ajax
, do not ask to order by key, which is what happens. The generation of my SELECT
is simply:
$.each(data.cidades,function(k,v){
options += "<option value='"+k+"'>"+v+"</option>";
});
$("#consumidor_cidade").html(options);
Try to give a
console.log(v)
inside each to see if he’s ordered– JuniorNunes
I believe your problem is related to how javascript stores its objects internally. I believe there’s no way you can guarantee the ordering of records through property. For this reason, I suggest you change your json to be an array instead of an object
– jlHertel
@jlHertel This was the problem: The need to send an Object. Before it was as an array, with no index. But there was the need to record index in return.
– William Aparecido Brandino