0
$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

2
  • Can you edit with other example, I can get what are you traying to do Commented Apr 7, 2015 at 3:35
  • john can you show your code? Commented Apr 7, 2015 at 4:02

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.