The asort()
method is used to sort arrays, without losing the index.
I do the sorting, both in the SQL search and in the array. However, when sending the data via JSON (using json_encode
), it reorders the keys.
Array example, sorted, assembled 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 ordered):
"cidades":{"4550":"AGUA BRANCA","8339":"ANADIA","3292":"ARAPIRACA","7509":"ATALAIA","21265":"BARRA DE SANTO ANTONIO","9109":"BARRA DE SAO MIGUEL","6127"
Examples of ajax generated options:
<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>
On receipt of ajax
, I do not ask to sort 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);