json_encode returns the asort() order

Asked

Viewed 316 times

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

  • 1

    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 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.

2 answers

2


The problem is not in the json_encode, as you yourself showed in the preview comes in the correct order.

The problem happens because in Javascript only arrays have defined order, but have no associative indices, so when making a json_encode PHP generates a JSON in object format - which has no defined order.

What you can do is send an extra attribute in the list with the order, or leave the index of the sequential array in the order you want to display and save the id and name in an internal structure.

Such a structure will maintain order.

$arr = [
  ['codigo'=>'4550', 'nome'=>'AGUA BRANCA'],
  ['codigo'=>'8339', 'nome'=>'ANADIA']
]

Or else specifying the order:

$arr = [
  ['codigo'=>'4550', 'nome'=>'AGUA BRANCA', 'order'=>0],
  ['codigo'=>'8339', 'nome'=>'ANADIA', 'order'=>1]
]

EDITION OF THE REQUISITOR TO SHOW THE RIGHT ANSWER

In mounting my array, it was done this way:

while ($resultado = pg_fetch_object($res)) {
    $cidades[] = array("cidade_id" => $resultado->cidade, "cidade_nome" => $resultado->cidade_nome);
}
/*envio*/
return json_encode(array("ok"=>true,"cidades" => $cidades));

And the assembly by jQuery was described in Hertel’s reply.

  • I even edited the title to "remove the blame" from json_encode, but as said in the question’s comment, in changing the need for receiving information, there was this disorder.

  • 1

    @Williamasimiliar as I put in the answer, Avascript does not maintain this order, you will have to send this data in a structure that has explicit this order to be able to reassemble the list.

  • 1

    @I added an example of a structure to maintain order.

1

As @Marcos has already commented, your problem is not in the role json_encode, but rather how the properties are indexed internally by the engine Javascript.

An alternative solution to your problem is to use an array and have multiple ordered objects within it:

<?php
$array = [
   [
     "indice" => 4550,
     "nome"   => "AGUA BRANCA"
   ],
   [
     "indice" => 8339,
     "nome"   => "ANADIA"
   ]
];

And in javascript do:

$.each(data.cidades,function(k,v){
    options += "<option value='"+v.indice+"'>"+v.nome+"</option>";
});
$("#consumidor_cidade").html(options);
  • Yes, I rode here and now it worked. I had to do what you said. As the two answered the same thing, I don’t know on whom I mark the right answer.

  • @Williamasimiliar Andean, the important thing is that your problem has been solved. Can mark either of the two that is great.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.