PHP排序数组按键'值'

PHP排序数组按键'值'

问题描述:

I have the following code which displays the results that I want. I'm trying to get it to sort on the key 'value' from the output below. So Eric, Eric 2, Eric 3

An example output of $resultnames is:

Array
(
[0] => Array
    (
        [Eric 2] => Asdf
    )

[1] => Array
    (
        [Eric] => Asdf
    )

[2] => Array
    (
        [Eric 3] => Asdf
    )

)

So the key is the first name and the value of that key is the last name. I'm trying to sort the array by first name

    foreach (array_chunk($uvugroups, 6, true) as $uvugroup)
    {       
        foreach ($uvugroup as $uvustate) {
            echo "<h4>Registrants</h4>";
            $fnames = explode( '|', $uvustate['fname'] );
            $lnames = explode( '|', $uvustate['lname'] );
            $resultnames = array();
            foreach ($fnames as $i => $key) {
              $resultnames[] = array($key => $lnames[$i]);
            }
            foreach ($resultnames as $resultname) {         
            foreach ($resultname as $fkey => $lkey) {
                echo "<ul>";
                echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
                echo "</ul>";
            }
            }               
        }
    }

I tried to use ksort in different places in the code, but it didn't seem to have an effect.

It's a bit hard because the expected output is not defined in the question, but with this code as the contents of the second foreach it should produce a list sorted by first name.

$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array_combine($fnames, $lnames);
ksort($resultnames);

echo "<ul>";
foreach ($resultnames as $fkey => $lkey) {
    echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
}
echo "</ul>";