我需要将我的数组渲染成这样的组:
[group]{A} abc alpha apple [/group]
但是,它还不想使用此代码:
sort($array, SORT_NATURAL | SORT_FLAG_CASE);
$batch = '';
$previous = strtoupper(substr($array[0], 0, 1));
foreach($array as $value) {
$firstLetter = strtoupper(substr($value, 0, 1));
if($previous !== $firstLetter){
echo "[group]{" . substr($firstLetter, 0,1) . "}\n" . $batch . "[/group]\n\n";
$batch = NULL;
}
else{
$batch.= $value."\n";
}
$previous = $firstLetter;
}
示例输入:
a
a
a
b
b
c
示例输出:
[submenu] (B)
a
a
a
[/group]
[submenu] (C)
b
[/group]
根据ElefantPhace'的建议输出在评论中:
[submenu] (A)
a
a
a
[end]
[submenu] (A)
[group]
[submenu] (A)
[group]
保持' $ previous = $ firstLetter;'在' else'之后给了我:
[submenu] (A)
a
a
a
[end]
[submenu] (B)
b
[group]
除了我错过了最后一项' c'
之外,这很好注意:我将$previous
留在了我的小组中。
答案 0 :(得分:1)
更简洁的方法是避免检查您是否使用了新的字母(if($previous !== $firstLetter)
内容),而是将第一个字母用作新数组中的索引,如下所示:
sort($array, SORT_NATURAL | SORT_FLAG_CASE);
$treeArray = array();
foreach($array as $el) {
$firstLetter = strtoupper(substr($el, 0, 1));
if(!(isset($treeArray[$firstLetter])) ) { $treeArray[$firstLetter] = array(); }
array_push($treeArray[$firstLetter], $el);
}
现在,您将拥有一个使用每个首字母作为索引的数组,因此您可以稍后循环显示如下:
foreach($treeArray as $letter => $contents) {
echo '[submenu] ' . $letter, PHP_EOL;
foreach($contents as $el) {
echo $el, PHP_EOL;
}
}
答案 1 :(得分:0)
解开代码后,您可以进行以下更改以获得所需内容:
$array = array("a", "ac", "ab", "bc", "be", "bd", "ce", "cg", "cf");
sort($array, SORT_NATURAL | SORT_FLAG_CASE);
$batch = '';
$output = '';
$previous = strtoupper(substr($array[0], 0, 1));
foreach($array as $value) {
//Get the first letter
$firstLetter = strtoupper(substr($value, 0, 1));
//Check if in a new group, otherwise add $value to current group
if($previous != $firstLetter) {
//In a new group, so prep for the next group.
$output .= "[group]{" . $previous . "}\n" . $batch . "[/group]\n\n";
$previous = $firstLetter;
$batch = '';
} else {
$batch .= $value."\n";
}
}
//Get the last batch.
$output .= "[group]{" . $previous . "}\n" . $batch . "[/group]\n\n";
print($output);
这将产生:
[group]{A}
a
ab
ac
[/group]
[group]{B}
bd
be
[/group]
[group]{C}
cf
cg
[/group]
希望能帮到你!
答案 2 :(得分:0)
使用您的方法的工作示例:
$array = ['alpha','abc','android','braces','barbs','brackets','crabs','cool'];
sort($array, SORT_NATURAL | SORT_FLAG_CASE);
$batch = '';
$previous = strtoupper(substr($array[0], 0, 1));
$count = count($array);
$i=0;
foreach($array as $value) {
$i++;
$firstLetter = strtoupper(substr($value, 0, 1));
if($previous !== $firstLetter || $i == $count){
if($i == $count) $batch.=$value."\n";
echo "[group]{".$previous."}\n" . $batch . "[/group]\n\n";
$batch = $value."\n";
}else{
$batch.= $value."\n";
}
$previous = $firstLetter;
}
输出:
[group] {A} abc alpha android [/ group]
[group] {B} barbs括号[/ group]
[group] {C}酷螃蟹[/ group]
不是很漂亮,但它有效!