Sort array array in PHP

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

so that it 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 value of the sub arrays from highest to lowest type in the first has this value 5, 3, 5 and I want it to be this way 5,5,3 no matter the order of the keys of the inter or external arrays more of these phaller that I put another example if in the place of 5,3,5 was 1,2,3,4,5,6 , 7,8,9,10,10,11,11 would thus be with the ordination 11,11,10,10,9,8,7,6,5,4,3,2,1

    
asked by anonymous 08.02.2017 / 03:37

3 answers

4

Sorting Algorithm

The sort algorithm that will be applied in this response is called Insertion Sort , or English, Insertion Sort , as it is best known. The way that such an algorithm works resembles a person arranging their hand in 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 your hand is made up 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 stays. For example, you received the 4 card. Such a card will be placed between the 6 and 3 cards, so that your hand remains sorted from highest to lowest: [9, 7, 6, 4, 3, 1] .

More generally, insert ordering works by traversing the list of values for each new item, and when a given condition is satisfied, insert the new element.

In the card game, the condition would be é maior que ..? . Given the new 4 element, it traverses the [9, 7, 6, 3, 1] list until 4 is greater than one element. From the top of the list:

  • 4 > 9? , no, continue;
  • 4 > 7? , no, continue;
  • 4 > 6? , no, continue;
  • 4 > 3? , yes, then insert new element (4) here;

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

Figure1:Illustrativepictureofhowinsertorderingworks.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, inserting in the list one item at a time, as this will guarantee that the item will be positioned in the correct place and we will have the list sorted in the signal. Our elements are removed from the $arr list:

$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 foreach directive and, for each item, we insert it into the list.

$result = [];

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

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

insert_sort (array $ result, mixed $ item)

The insert_sort function receives two parameters: the list where we want to insert the item and the item to insert. The logic of the function is exactly that explained in the algorithm at the beginning of the response:

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 out: scroll through the entire list until the condition is true. Enter the new value and return the sorted list. This way, at the end, the $result list will be:

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

You can see the code working at repl.it .

Note : The condition used for sorting varies as needed. In this case, our list items are of type array and we want to sort in a decreasing order according to the value in the first position. With the function array_values , we return the list of all values of array and, when accessing the index [0] , we return only the first, thus ordering in relation to 5, 3, 5 , as given in the statement .

Optimized version

The same result can be obtained as follows:

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

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

  

You can see the code working at repl.it .

Documentation: array_splice , array_values , usort , current

    
08.02.2017 / 11:44
0

Turning to performance, since your internal indexes do not seem to follow any pattern either, I've made a workaround 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>";
    
08.02.2017 / 11:06
-5

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

$exemplo = array_reverse($var);

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

$exemplo = arsort($var);

Sorting array documentation

    
08.02.2017 / 09:52