Organize array in alphabetical order

Asked

Viewed 1,758 times

2

Good when I want to organize an array in alphabetical order based on an array field I do so:

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

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

This works perfectly, but wanted to simplify everything in a single function, to facilitate when I call.

They try to do so:

    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") );

Mistakes :

NOTICE Undefined variable: campo on line number 14

NOTICE Undefined index:  on line number 14

Note: I am using PHP 7.2

  • This problem is pq vc is putting a string in place of a parameter in the function Ordena_Array.

  • Which version of PHP you are using?

  • I’ll edit the question, it’s not very clear.

  • So I changed the question.

3 answers

3


It is possible.

And it is possible to simplify this code using Closures (or anonymous functions).

Your problem is that the internal closure has no access to the variable $campo. This is because of the scope, so you need to give access to this variable for internal closure (using use).

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

Do so:

<?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 the naming convention of functions.

I suggest using ordena_array.

Fiddle: https://ideone.com/ygGstF

  • Okay, thank you so much for the help and the tip. It worked.

0

IF YOU WISH TO SORT AND ALSO CHANGE THE INDEX:

According to 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 sorted alphabetically with changes in indexes

IF YOU SNITCH ORDER AND MAINTAIN THE INDEX:

According to 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 = lemon
c = watermelon

The array has been sorted alphabetically, the indexes have been maintained

  • Okay, but I don’t want to echo the result I want to keep the variable $array to be used in a report.

0

There are two issues in its implementation.

The first, which is the error you are receiving, is that the variable $campo is not available when the function is executed. The variable must be added to the function context. In this case, you can use anonymous functions and use the 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 the array ordained. The array is ordered by reference, so must return the array which has been passed as 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;
}

Code in operation: https://3v4l.org/oMtYS

Browser other questions tagged

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