How to sort an Array alphabetically in PHP?

Asked

Viewed 775 times

1

I have an nxm array which I call $tabela.

This array has some inside data organized as follows:

| Papel1 | Hora1 | Valor1 | Erro  | B |
| Papel2 | Hora2 | Valor2 | OK_Ok | A |
| Papel3 | Hora3 | Valor3 | Falha | C |
| Papel4 | Hora4 | Valor4 | OK_OK | A |

All table data is extracted from a table mysql, except the last column I insert into the array based on some conditions.

My question is, how to alphabetize all rows of the array based on the last column? It would have to return this way:

| Papel2 | Hora2 | Valor2 | OK_Ok | A |
| Papel4 | Hora4 | Valor4 | OK_OK | A |
| Papel1 | Hora1 | Valor1 | Erro  | B |
| Papel3 | Hora3 | Valor3 | Falha | C |
Array ( [0] => Array ( [0] => MIL EUA [1] => 2018-03-05 14:00:13 [3] => 168.99 [2] => 2018-03-05 15:00:11 [4] => 168.99 [5] => Atraso entre os servidores de 59 minutos ) [1] => Array ( [0] => TRIGQQNP [1] => 2018-03-05 14:00:15 [3] => 3800.00 [2] => 2018-03-05 15:00:12 [4] => 3800.00 [5] => Atraso entre os servidores de 59 minutos ) )

2 answers

2

If they are columns that came from a database as you stated in:

All table data is extracted from a mysql table

So before inserting into the array you could already bring sorted using ORDER by (ASC for growing and DESC for unbeliever), something like:

SELECT id, nome, foo, bar, ultimacoluna
FROM tabela
WHERE <condica>
LIMIT <limite>
ORDER by ultimacoluna ASC

Then in the while or foreach which is probably using to add the items in the new array they will already be in alphabetical order (may depend/vary from the coding system).

However, if the problem is another, I recommend that you explain the behavior of the code and show an example of the array using print_r or var_dump so we can actually see what the shape of your truth array looks like for only then we can suggest the most efficient way of truth for your specific case.

1


You can use usort()

function cmp($a, $b)
{
    return strcmp($a["nome_ultimo_campo"], $b["nome_ultimo_campo"]);
}

usort($tabela, "cmp");

In that question was raised something like what you need.

  • In the case of the example I put above, what would be the name of the last field

  • would be the "name" of the last index..

  • I did not name the index, I must put the column number?

  • I believe it works; in that case it would be without the quotation marks ("")

Browser other questions tagged

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