简体   繁体   English

按前2个字母分组或列出单词

[英]Group or list words by first 2 letters

I'd like to list/group words by the first two letters but I can't get my head around it. 我想按前两个字母列出/分组单词,但我无法理解。 I guess I can I can do a substr() and check against while looping but I'm not sure if this is the way to do it. 我想我可以做一个substr()并在循环时进行检查,但是我不确定这是否是这样做的方法。

Something like: 就像是:

if (substr($word, 0, 2) == 'aa') {
 echo $word;
}

What I'm trying to achieve: Words get sorted first by their starting letter, eg A, B, C etc. On the A page you have the words sorted by the first 2 letters, eg aa, ab, ac etc. 我要达到的目标:单词首先按其首字母排序,例如A,B,C等。在A页面上,您将单词按前2个字母排序,例如aa,ab,ac等。

An example for this is http://www.urbandictionary.com/browse.php?word=aa . 例如: http://www.urbandictionary.com/browse.php?word=aa They do exactly what I'm after. 他们正是我所追求的。

Help/thoughts appreciated! 帮助/想法表示赞赏!

If you have a bunch of words, put them grouped together in an array. 如果您有一堆单词,请将它们组合成一个数组。

for example: 例如:

<?php
$myWords = array ("hello", "hell", "ape", "word", "appel");
$myGroupedArr = array();
foreach ($myWords as $oneWord){
  $firstTwo = substr($oneWord,0,2);
  $myGroupedArr[$firstTwo][] = $oneWord;  
}
echo "<pre>";
print_r($myGroupedArr);
echo "</pre>";
?>

I would sort not only by the first letter, but by the whole word, or at least by the first two letters. 我不仅要按首字母排序,还要按整个单词或至少按前两个字母排序。

Then, you can indeed use substr to get the first two letters of the first word. 然后,您确实可以使用substr获取第一个单词的前两个字母。 You can then enter the loop, and check the first two letters of the word in the loop, with the two letters you got before. 然后,您可以进入循环,并检查循环中单词的前两个字母以及之前获得的两个字母。

If they differ, you know you got a new group. 如果他们不同,您就会知道有一个新的小组。 You can echo a group header and store the new to letters to compare with in the following iterations. 您可以回显组标题并将新的字母存储为字母,以便在以下迭代中进行比较。

// Words in a sorted array.
$words = array( ...... );
asort($words);

$currentGroup = '';
foreach ($words as $word)
{
    $newGroup = substr($word, 0, 2);

    if ($newGroup !== $currentGroup)
    {
        // A new group is starting.
        echo "=== $newGroup ===<br/>";
        $currentGroup = $newGroup;
    }

    echo $word . '<br/>';
}

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

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