简体   繁体   中英

How to sort an array based on a value

$arr['a']['studentname'] = "john";

$arr['b']['studentname'] = "stefen";

$arr['c']['studentname'] = "alex";

is it possible to sort using user defined functions:

usort( $arr )


uasort( $arr )


uksort( $arr )

so based on value which i need to pass, the array should be sorted! expected output:

if the current value then

Array
(
    [c] => Array
        (
            [studentname] => alex

        )

    [a] => Array
        (
            [studentname] => john

        )

    [b] => Array
        (
            [studentname] => stefen

        )

)  

if the current value then

 Array
    (

[b] => Array
            (
                [studentname] => stefen

            )
 [a] => Array
            (
                [studentname] => john

            )
        [c] => Array
            (
                [studentname] => alex

            )

    )  

thanks in advance

If I understood the question, you can use a simple string compare callback:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

// A-Z
uasort($arr, function($a, $b) {
  return strcmp($a['studentname'], $b['studentname']);
});

print_r($arr);

// Z-A
uasort($arr, function($a, $b) {
  return strcmp($b['studentname'], $a['studentname']);
});

print_r($arr);

Try this:
For PHP version > 5.3:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

uasort($arr, function($a, $b) {
    return strcmp($a['studentname'], $b['studentname']);
});

For PHP version < 5.3:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

function sort_by($a, $b) {
    return strcmp($a['studentname'], $b['studentname']);
}

uasort($arr, 'sort_by');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM