PHP按键排序数组'值'

时间:2015-11-24 20:30:44

标签: php arrays sorting

我有以下代码显示我想要的结果。我试图让它对关键的价值进行排序'从下面的输出。所以Eric,Eric 2,Eric 3

$resultnames的示例输出是:

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

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

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

)

因此密钥是名字,该密钥的值是姓氏。我试图按名字

对数组进行排序
    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>";
            }
            }               
        }
    }

我尝试在代码中的不同位置使用kso​​rt,但它似乎没有效果。

1 个答案:

答案 0 :(得分:0)

它有点难,因为预期的输出没有在问题中定义,但是这个代码作为第二个foreach的内容,它应该产生一个按名字排序的列表。

$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>";