1

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...

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.


any idea how to do it?

Leader
  • 68
  • 7
  • 1
    Make your question clear with some raw input data+ code what you tried+where you stuck+desired output what you want. Statements and links will not going to help any-one. – Alive to die - Anant Sep 06 '17 at 13:23
  • Possible duplicate of [Group array results in Alphabetic order PHP](https://stackoverflow.com/questions/14210480/group-array-results-in-alphabetic-order-php) – Hamza Zafeer Sep 06 '17 at 13:27
  • Related and a very good candidate for code extension to suit your case: https://stackoverflow.com/questions/43371496/group-array-elements-by-letter-range – mickmackusa Sep 06 '17 at 13:59

2 Answers2

1

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>";
}
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
  • 1
    Thank you for answering, your code worked nicely... but the other answer is just too sexy to for me... XD – Leader Sep 06 '17 at 13:59
1

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80