sort multidimensional array php

Asked

Viewed 878 times

6

I have the following array returned from a webservice (in the image I identify what I want, below the text for copy): inserir a descrição da imagem aqui

Array
(
    [DataTable] => Array
        (
            [ID] => STOCK
            [Line] => Array
                (
                    [0] => Array
                        (
                            [Fields] => Array
                                (
                                    [0] => Array
                                        (
                                            [FieldID] => ItemCode
                                            [Value] => 1GADEME010001
                                        )

                                    [1] => Array
                                        (
                                            [FieldID] => ItemName
                                            [Value] => Sucata de ferro
                                        )

                                    [2] => Array
                                        (
                                            [FieldID] => FrgnName
                                            [Value] => Array
                                                (
                                                )

                                        )

                                    [3] => Array
                                        (
                                            [FieldID] => ItmsGrpCod
                                            [Value] => 112
                                        )
                    [0] => Array
                        (
                            [Fields] => Array
                                (
                                    [0] => Array
                                        (
                                            [FieldID] => ItemCode
                                            [Value] => 1GADEME010001
                                        )

                                    [1] => Array
                                        (
                                            [FieldID] => ItemName
                                            [Value] => Armário de ferro
                                        )

                                    [2] => Array
                                        (
                                            [FieldID] => FrgnName
                                            [Value] => Array
                                                (
                                                )

                                        )

                                    [3] => Array
                                        (
                                            [FieldID] => ItmsGrpCod
                                            [Value] => 112
                                        )

Since the array has n records, I want to sort the array by name, which is underlined in red. I tried to use https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value but without success.

  • Take a look to see if my answer helps :)

  • 1

    Put text instead of photo please.

  • @Guilhermenascimento already added in code

3 answers

5

Well, I think I’d do it this way. Just use the function usort.

usort($dados['dataTable']['lista'], function ($a, $b){ 
  return strcmp($a['fields'][0]['name'], $b['fields'][0]['name']); 
});

The function usort has the purpose of ordering a array according to a callback passed by the user (the programmer, in this case, hehehe).

The Callback should contain two parameters: These are the items, passed two by two, during the internal iteration that PHP will do.

According to the comparison is that it is done there in the callback is that the array will be ordained.

You shall return 1, -1 or 0

Value 1 - When you want the element $a be the first in relation to $b

Value 0 - When sorting position remains the same.

Value -1 When the sorting position of $b should be greater than $a.

So why did I use strcmp on the return?

This function, according to the Handbook:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

So, look at the following values to get an idea of our example quoted above:

strcmp('a', 'b'); // int(-1)

strcmp('b', 'a'); // int(1)

strcmp('b', 'b'); // int(0)
  • This is advanced logic, and mine is for laymen :D

  • 1

    I thought of quoting the sortBy, of Collection of Laravel. But apparently you’ve solved :)

  • It would be interesting to comment that it compares the current index with the next one, and so on. Practically a Bubble Sort.

  • I don’t know what that is... You can add the answer if you want :)

  • @Wallacemaxters, I read online that Bubble Sort was not a good option. But in the code you have placed, I think you will have a small error when fetching the array position. It will not be $a['Fields'][1]['value'] to fetch?

3

The logic to order this type of structure is to assemble a simple array that will be ordered, keeping the association keys.

$dados = array( // DADOS TESTE
    'dataTable' => array(
        'lista' => array(
            0 => array(
                'fields' => array(
                    0 => array(
                        'name' => 'B'
                    )
                )
            ),
            1 => array(
                'fields' => array(
                    0 => array(
                        'name' => 'D'
                    )
                )
            ),
            2 => array(
                'fields' => array(
                    0 => array(
                        'name' => 'C'
                    )
                )
            ),
            3 => array(
                'fields' => array(
                    0 => array(
                        'name' => 'A'
                    )
                )
            ),
        )
    )
);

$arraySort = array(); // ARRAY MONO DIMENCIONAL QUE VAI SER ORDENADO 
foreach ($dados['dataTable']['lista'] as $k => $list){
    $arraySort[$k] = $list['fields'][0]['name']; // SET AO DADO RELEVANTE PARA A ORDENAÇÃO
}
asort($arraySort); // ORDENA MANTENDO AS CHAVES

$listaDados = array(); // ARRAY QUE IRA COPIAR "dados", MAS ORDENADO
foreach ($arraySort as $k => $value){
    $listaDados[] = $dados['dataTable']['lista'][$k];   // COPIA OS DADOS DO $k INDICADO
}

$dados['dataTable']['lista'] = $listaDados;

var_dump($dados);

0

I believe that you yourself can create a simple algorithm for sorting, can even be based on Bubble Sort.

For this, use a foreach that goes through all the keys of the array:

foreach ($array as $chave => $valor) {}

Obs: Possibly this is the most difficult way, but sometimes creating your own methods instead of always using ready-made functions helps you develop your logical reasoning.

  • 1

    I accept your answer, but it should be a comment to the post and not an answer, because in fact it is not. What you advised I tried, but if you did not have difficulties, I would not ask the question. Anyway thanks for the help :)

  • Sorry, I’m new around here... If you haven’t found a solution yet I can try to create the method for you. I just need the complete structure of the array with some test data and if I can solve your problem I put as answer.

  • Douglas, your participation is legal, and your response on the right track. If you can elaborate a little more the answer, will attract more positive votes. You can [Edit] your post at any time to add more data.

  • Thanks for the Bacco tip! Later I will try to create a well-commented algorithm to help our colleague and replace my old answer.

Browser other questions tagged

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