sort array by date

Asked

Viewed 203 times

1

I created a function that makes the selectt in the database and returns the data in array and now I want to sort its answer by date example

Response returned from function

    Array ( [dados-0] => Array ( [valor-0] => 300 [date-0] => 26/2/2019 )
        [dados-1] => Array ( [valor-1] => 150 [date-1] => 26/2/2019 ) 
        [dados-2] => Array ( [valor-2] => 150 [date-2] => 26/3/2019 ) 
        [dados-3] => Array ( [valor-3] => 5000 [date-3] => 9/3/2019 ) 
        [dados-4] => Array ( [valor-4] => 300 [date-4] => 10/3/2019 ) 
      ) 

And so on I want to order from the order but old to older getting like this:

 Array ( [dados-0] => Array ( [valor-0] => 300 [date-0] => 26/2/2019 )
    [dados-1] => Array ( [valor-1] => 150 [date-1] => 26/2/2019 )
    [dados-3] => Array ( [valor-3] => 5000 [date-3] => 9/3/2019 )  
    [dados-2] => Array ( [valor-2] => 150 [date-2] => 10/3/2019 )   
    [dados-4] => Array ( [valor-4] => 300 [date-4] => 26/3/2019 ) 
  ) 

Someone can help me?

3 answers

2

You can make SELECT return you sorted as you want, rather than having to work it out in php. For this, at the end of your SELECT you need to put: ORDER BY nome_campo_data. By default sql sorts in ascending order.

  • 1

    The ideal is to do this!

  • Yes I thought about it but I would have to modify several parts of the function I created, because it is not accepting the order by because it goes through a procedure before making the request to the bank, so I’m trying to find a way I can arrange without having to use the order by, and also the dates are separate would have to create an as to modify and merge to then give the ordeby

1


I had to redo the answer.

To do what you need I created two functions. One to change date values recursively. And the other to get the first date found in the array to be able to sort.

Are these functions:

    // função que aplica uma função passada por parâmetro em todos os elementos do array
    function array_map_recursive(callable $func, array $array){
        $res = [];
        foreach ($array as $k => $v)
            $res[$k] = is_array($v) ? array_map_recursive($func, $v) : $func(trim($v));
        return $res;
    }

    // função que recupera a primeira data encontrada em um array
    function getDataInArray(array $array){
        foreach($array as $val){
            if(is_array($val)) return getDataInArray($array);
            if(preg_match('/\d{2,4}\-\d{1,2}\-\d{1,2}(?=$)/', $val)) return $val;
        }
        return false;
    }

Then I used the functions as follows (commented code):

    // altera o array para ser ordenado ( formato será por exemplo 2015-02-30 )
    $new = array_map_recursive(function($v){
        // identifica se é uma data. Se for uma data retorna uma nova data com o formato americano.
        return preg_match('/\d{1,2}\/\d{1,2}\/\d{2,4}(?=$)/', $v) ? date("Y-m-d", strtotime(str_replace("/", "-", $v))) : $v;
    }, $dados);

    // ordena o array preservando as chaves
    uasort($new, function($a,$b){
        return strcmp(getDataInArray($a), getDataInArray($b));
    });

    // altera o array para ser usado ( formato será por exemplo 30/02/2015 )
    $dados = array_map_recursive(function($v){
        // identifica se é uma data. Se for uma data retorna uma nova data com o formato brasileiro.
        return preg_match('/\d{2,4}\-\d{1,2}\-\d{1,2}(?=$)/', $v) ? date("d/m/Y", strtotime(str_replace("/", "-", $v))) : $v;
    }, $new);

    // exibe
    print_r($dados);

Example script in Ideone

  • And if there’s any more data like it comes back that way." Array ( [data-0] => Array ( [value-0] => 300 [date-0] => 26/2/2019 ) [data-1] => Array ( [value-1] => 150 [date-1] => 26/2/2019 ) [data-2] => Array ( [value-2] => 150 [date-2] => 26/3/2019 ) [data-3] => Array ( [value-3] => 5000 [date-3] => 9/3/2019 ) [data-4] => Array ( [value-4] => 300 [date-4] => 10/3/2019 ) )"

  • each data has an array ai i have q sort by date q this within the array

  • @Cyberhacker the problem is that this ai array is multidimensional! Unlike the array you posted!

  • @Cyberhacker how do you want the result of this array? Ask the question.

  • @Cyberhacker tomorrow I create a solution. Today I think I will not get.

  • yes, because I thought it would order only by date and the other would inrelavar however I noticed q n worked of the check q wanted ai put in a multidimensional array oara see if it fixed and I’m breaking the head here

  • @Cyberhacker did the editing for you

  • our thank you very much, now I will read and study your code to better understand thank you

  • @Cyberhacker quiet my dear!

Show 4 more comments

0

You could use the function sort PHP if you had your dates in the "Year-Month-Day" format, or if your dates were a timestamp.

By the way, this is the way I would recommend you record in your database. The BD itself could sort the result for you if it was recorded in a standard format, "Day/Month/Year" will probably give you more headache in the future.

What remains is to convert the format of your dates, organize them, and then convert them back to the original format.

$datas = [
    '29/02/2016',
    '30/02/2015',
    '27/02/2013',
    '28/02/2014',
];

// converte datas para timestamp
foreach ($datas as $data) {
    $timestamps[] = strtotime(str_replace('/', '-', $data));
}

// ordena 
sort($timestamps);

// converte timestamp para datas
foreach ($timestamps as $timestamp) {
    $data_ordenado[] = date('m/d/Y', $timestamp); 
}

// imprime o array
// 02/27/2013, 02/28/2014, 03/02/2015, 02/29/2016
var_dump($data_ordenado);

Browser other questions tagged

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