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

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本