du060334 2015-11-24 20:30
浏览 41
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dougou3871 2015-11-24 20:50
    关注

    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>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应