Sort array in PHP

Asked

Viewed 1,393 times

3

array (0 => array 1 => int 5 1 => array 2 => int 3 2 => array 8 => int 5);

so that he stays that way

array (0 => array 1 => int 5 2 => array 8 => int 5 1 => array 2 => int 3 );

I want to sort this array as follows by the integer values of the subarrays from the largest to the smallest type in the first has this value 5, 3, 5 and I want it to stay like this 5,5,3 no matter the order of the keys of the inter or external arrays more of these Allot that I put another example if instead of 5,3,5 was 1,2,3,4,5,6,7,8,9,10,11,11 would look like this with the ordination 11,11,10,10,10,9,8,7,6,5,4,3,2,1

  • 1

    arsort or rsort -> https://secure.php.net/manual/en/function.arsort.php https://secure.phnet/manual/pt_BR/function.rsort.php, that’s what you need?

3 answers

6


Sorting Algorithm

The sort algorithm that will be applied in this answer is called Sorting by Insertion, or English, Insertion Sort, as is best known.

The way such an algorithm works resembles a person organizing his hand into a card game. Imagine that in this game you have 5 cards in your hand, sorted numerically. Disregarding the different suits and focusing only on the numbers, let’s assume that your hand is composed of [9, 7, 6, 3, 1]. When you receive a new card in the round, you will place it in your hand so that the order remains. For example, you received the letter 4. Such a card will be positioned between the cards 6 and 3, so that your hand remains ordered from the largest to the smallest: [9, 7, 6, 4, 3, 1].

In more general terms, insertion sorting works by scrolling through the list of values for each new item and, when a particular condition is met, enter the new element.

In the card game, the condition would be é maior que ..?. Given the new element 4, scroll through the list [9, 7, 6, 3, 1] until 4 is larger than an element. From the beginning of the list:

  • 4 > 9?, no, go on;
  • 4 > 7?, no, go on;
  • 4 > 6?, no, go on;
  • 4 > 3?, yes, then enter the new element (4) here;

Getting the final list [9, 7, 6, 4, 3, 1].


inserir a descrição da imagem aqui

Figure 1: Figure illustrating how the insertion sorting works. Source: w3resource


PHP code

First, let’s assume that our list of elements is defined as:

$result = [];

As we wish to order a complete list, we will follow the idea presented in the algorithm, entering one item at a time in the list, as this will ensure that the item will be positioned in the correct place and we will have the ordered list in the signal. Our elements are removed from the list $arr:

$arr = [
    0 => [1 => 5], 
    1 => [2 => 3], 
    2 => [8 => 5]
];

In PHP, to go through all the items in a list, we can use the directive foreach and, for each item, we insert it in the list.

$result = [];

foreach ($arr as $item)
{
    $result = insert_sort($result, $item);
}

The function insert_sort we will define soon. What we are doing in this passage is: for each $item of $arr, insert into the list $result and update the value of $result containing the new item.

insert_sort(array $result, Mixed $item)

The function insert_sort receives two parameters: the list where we want to insert the item and the item to be inserted. Function logic is exactly the one explained in the algorithm at the beginning of the answer:

function insert_sort($result, $item)
{
    // Variável de controle da posição na lista:
    $index = 0;

    // Percorre a lista:
    foreach ($result as $j => $value)
    {
        // Verifica a condição: (novo item) > (item da lista)?
        if (array_values($item)[0] > array_values($value)[0])
        {
            // Sim, então pare de percorrer a lista
            break;
        }

        // Não, então continue para a próxima posição:
        $index++;
    }

    // O novo item será inserido na posição $index
    // Para isso, precisamos abrir o espaço na lista com a função array_splice:
    array_splice($result, $index, 0, array($item));

    // Retorne a lista ordenada:
    return $result;
}

As commented: Scroll through the entire list until the condition is true. Enter the new value and return to the sorted list. Thus, at the end, the list $result will be:

Array
(
    [0] => Array
        (
            [1] => 5
        )
    [1] => Array
        (
            [8] => 5
        )
    [2] => Array
        (
            [2] => 3
        )
)

You can see the code working on repl it..


Note: The condition used for sorting varies depending on the need. In this case, our list items are of the type array and we want to sort down according to the value in the first position. With the function array_values, return the list of all values of array and, when accessing the index [0], we return only the first, ordering, in this way, in relation to the values 5, 3, 5, as stated above.


Optimized version

The same result can be obtained as follows::

usort($arr, function ($a, $b) {
  return current($b) - current($a);
});

In this case, the list itself $arr will be sorted. The executed logic is exactly the same, only written with fewer lines, due to the use of the function usort and current.

You can see the code working on repl it..


Documentation: array_splice, array_values, usort, current

  • Guy worked out got you a better explained By the guy genius reasoning hit me hard to get this results you got with few lines!

  • Is there any particular part that is hard to understand? Well, I will improve the explanation as a whole. It is very weak indeed.

  • @Joao, forgive the delay, but I edited the answer with a more complete explanation. See if you understand now.

  • Dude cool that reasoning now it’s clear thank you very much!

  • If possible, mark the answer as valid to indicate that the problem has already been solved.

  • ok how do I am new in the forum?

  • On the left side of the answer, has the voting system. Just below the down arrow, there is the button with format of a "right", just click on it.

  • Anderson another question how do I access the keys of the sub array that are as value! example I want to access the values of the keys in the example above 1, 8, 2

  • I got it this way if you have a better idea comment there! for($i=0; $i <Count($result); $i++){ foreach($result[$i] as $position => $value){ var_dump($position); } }

  • @Joao, https://repl.it/Fe1w/0

Show 6 more comments

0

Giving up performance, since your internal indexes don’t seem to follow any pattern either, I made a solution for you:

echo "<pre>";
$arr = array(0 => array(1 => 5), 1 => array(2 => 3), 2 => array(8 => 5));

$arr = array_values($arr);

$tmp = array();
foreach($arr as $key => $value) {
    $val = array_values($value);
    array_push($tmp, $val[0]);
}

rsort($tmp);

foreach($tmp as $key => $value) {
    $arr[$key] = array($value);
}

print_r($arr);
echo "</pre>";
  • But so the content of array internal is lost, right? In the final result, all the indices of the array internal are zeros.

  • 1

    As he speaks little of the contents I did not store them, but it would be possible if necessary.

-6

Just use a array_reverse with the variable that is the group of arrays that you want to invert...

$exemplo = array_reverse($var);

Now if you want to re-organize all arrays in ascending or descending order, you can use arsort (from largest to smallest) or asort (from smallest to largest).

$exemplo = arsort($var);

Documentation about Sorting array

  • 1

    It wouldn’t hurt to have searched a little on the php site...

Browser other questions tagged

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