简体   繁体   English

组数组结果按字母顺序排列(PHP)(续)

[英]Group array results in Alphabetic order PHP (continued)

I'm sorry for the uncreative title. 不好意思,我很抱歉。

I'm trying to group my array alphabetically. 我正在尝试按字母顺序对数组进行分组。 The accepted answer in this question (by Hugo Delsing) helped greatly to my task, but I still want to take things a bit further... 这个问题(Hugo Delsing)接受的答案对我的任务有很大帮助,但我仍然想进一步做些事情...

here's my current code: 这是我当前的代码:

$records = ['7th Trick', 'Jukebox', 'Dynamyte', '3rd Planet'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE);

foreach($records as $val) {
    $char = strtolower($val[0]);

    if ($char !== $lastChar) {
        if ($lastChar !== '') echo "</ul>";

        echo "<h2>".strtoupper($char)."</h2><ul>";
        $lastChar = $char;
    }

    echo '<li>'.$val.'</li>';

}
echo "</ul>";

I want to make things so that non-alphabetic items would get grouped together instead of separated individually. 我想做一些事情,以便非字母项目可以组合在一起,而不是单独分开。


example: 例:

"7th Trick" and "3rd Planet" get grouped together as non-alphabetic instead of displayed separately under "7" and "3" category respectively. “ 7th Trick”和“ 3rd Planet”被分组为非字母,而不是分别在“ 7”和“ 3”类别下显示。


any idea how to do it? 知道怎么做吗?

Remove the alphas from the array and show them after printing the alphas. 从数组中删除字母,并在打印字母后显示它们。

<?php
$records = ['7th Trick', 'Jukebox', 'Dynamyte', '3rd Planet'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE);

$alpha = array();
$non_alpha = array(); 
foreach($records as $val) {
   if (ctype_alpha($val[0])) {
      $alpha[] = $val; 
   } else { 
      $non_alpha[] = $val; 
   }
}
foreach($alpha as $val) {
    $char = strtolower($val[0]);

    if ($char !== $lastChar) {
        if ($lastChar !== '') echo "</ul>";

        echo "<h2>".strtoupper($char)."</h2><ul>";
        $lastChar = $char;
    }

    echo '<li>'.$val.'</li>';

}
echo "</ul>";
if (sizeof($non_alpha) > 0) { 
   echo "<h2>Digits</h2><ul>";
   foreach ($non_alpha as $val) { 
      echo '<li>'.$val.'</li>';
   } 
   echo "</ul>";
}

You can just add one line to your existing code to accomplish this. 您只需在现有代码中添加一行即可完成此操作。

$char = strtolower($val[0]);

// Convert $char to one value if it isn't a letter
if (!ctype_alpha($char)) $char = 'Non-alphabetic';

if ($char !== $lastChar) {

The rest of it should work the same. 其余的应该都一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM