Arrange array in alphabetical order

2

When I want to sort an array alphabetically based on an array field I do this:

// Compara se $a é maior que $b
function cmp($a, $b) {
    return $a['nome'] > $b['nome'];
}

// Ordena
usort($produtos, 'cmp');

This works perfectly, but I wanted to simplify everything in a single function, to make it easier for me to call it.

Try to do this:

    function Ordena_Array ($array, $campo) {

    // Compara se $a é maior que $b
    function cmp($a, $b) {
        return $a[$campo] > $b[$campo];
    }

    // Ordena
    return usort($array, 'cmp');
}

Example of how I tried to do

 $array = array(
array( 'nome' => 'Alexandre',   'idade' => '65' ),
array( 'nome' => 'Alex',    'idade' => '33' ),
array( 'nome' => 'Zezinha', 'idade' => '29' ),
array( 'nome' => 'Rosana',  'idade' => '64' )
);

function Ordena_Array ($array, $campo) {

    // Compara se $a é maior que $b
    function cmp($a, $b) {
        return $a[$campo] > $b[$campo];
    }

    // Ordena
    return usort($array, 'cmp');
}


// Mostra os valores
print_r( Ordena_Array ($array, "nome") );

Errors:

NOTICE Undefined variable: campo on line number 14

NOTICE Undefined index:  on line number 14

Note: I'm using PHP 7.2

    
asked by anonymous 31.08.2018 / 15:20

3 answers

2

It is possible.

And you can simplify this code by using Closures (or anonymous functions).

Your problem is that the internal closure does not have access to the $campo variable. This is because of the scope, so you need to give this variable access to the internal Closure (using use ).

Another issue is that you need to modify the array inside the function and return it, and not return the result of the function usort directly.

Do this:

<?php

function Ordena_Array($array, $campo) {
    usort($array, function ($a, $b) use ($campo) {
        return $a[$campo] > $b[$campo];
    });
    return $array;
}

$array = array(
    array( 'nome' => 'Alexandre',   'idade' => '65' ),
    array( 'nome' => 'Alex',    'idade' => '33' ),
    array( 'nome' => 'Zezinha', 'idade' => '29' ),
    array( 'nome' => 'Rosana',  'idade' => '64' )
);

var_dump(Ordena_Array($array, "nome"));

I suggest not naming functions with uppercase letters in PHP because it escapes from the naming convention of functions.

I suggest using ordena_array .

Fiddle: link

    
31.08.2018 / 15:34
0

There are two issues in your implementation.

The first, which is the error you are getting, is that the $campo variable is not available when the function is executed. The variable must be added to the context of the function. In this case, you can use anonymous functions and use use to add the variable:

// Compara se $a é maior que $b
$callback = function ($a, $b) use ($campo) {
    return $a[$campo] > $b[$campo];
};

// Ordena
usort($array, $callback);

The other point is that usort returns a boolean and not array ordered. The array is ordered by reference, so you should return the array that was passed as a parameter:

function Ordena_Array ($array, $campo) {
    // Compara se $a é maior que $b
    $callback = function ($a, $b) use ($campo) {
        return $a[$campo] > $b[$campo];
    };

    // Ordena
    usort($array, $callback);

    return $array;
}

Working Code: link

    
31.08.2018 / 15:34
0

IF YOU WANT TO ORDER AND ALSO CHANGE THE INDEX:

According to the PHP documentation: PHP SORT

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The return will be:

  

fruits [0] = apple
  fruits [1] = banana
  fruits [2] = lemon
  fruits [3] = orange

The array has been ordered alphabetically by changing the indexes

IT IS DEDICATED TO ORDER AND MAINTAIN THE INDEX:

According to the PHP documentation: PHP ASORT

<?php
$frutas = array("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");
asort($frutas);
foreach( $frutas as $chave => $valor ){
    echo "$chave = $valor\n";
}
?>

The return will be:

  

b = banana
  a = orange
  d = limao
  c = watermelon

The array was sorted alphabetically, indexes were maintained

    
31.08.2018 / 15:27