3
In php, when we want to order a array
in a customised way we can use the function usort
.
I know that for this function to work, we must use values 1
, 0
and -1
.
In case, if I wanted to order this array
down in descending order, we could do so:
$array[0]['preco'] = 10.00;
$array[1]['preco'] = 25.00;
$array[2]['preco'] = 20.00;
usort($array, function ($a, $b)
{
return $b['preco'] > $a['preco'] ? 1 : 0;
});
The result would be:
[
[
"preco" => 25.0,
],
[
"preco" => 20.0,
],
[
"preco" => 10.0,
],
]
]
If I reversed the variables in the comparison, the result would be different:
usort($array, function ($a, $b) {
$a['preco'] > $b['preco'] ? 1 : 0;
});
The result would be:
[
[
"preco" => 10.0,
],
[
"preco" => 20.0,
],
[
"preco" => 25.0,
],
]
I also usually reduce the comparison by simply doing a subtraction operation, when I want to order backwards:
usort($array, function ($a, $b)
{
return $b['preco'] - $a['preco'];
});
I know that if we used the value 0
for all comparisons, the results would remain in the same position.
I know how to change the ordering of values, but I don’t understand how php does it internally.
And it is possible to do this operation in Python
also.
Example:
lista = [1, 2, 3]
lista.sort(lambda a,b: b-a)
#[3, 2, 1]
How is this comparison made, so that the languages knew which is the first and which is the second?
What represents the 1
or the -1
, internally, for these ordination functions?
You can use the spaceship :D in this function ai. There was no missing php tag there?
– rray
@rray no, why the
Python
also does the same thing.– Wallace Maxters
And who gave negative, could explain how I can improve the question?
– Wallace Maxters
Got it, I thought it was php’s question.
– rray