给定一个数组,有没有办法输出一个4列html表,其中包含字母排序的数组内容列表,突出显示字母表的第一个索引字母(仅当数组中有一个元素以任何给定的字母表字母)?
换句话说,我说有阵列:
$array = ('apple','pear','banana','pomegranate','orange','peach','clementine');
我想要这样的输出:
_________________________________________
|A |C |P |O |
|apple |clementine |pear |orange |
|B |O |pomegranate | |
|banana |orange |peach | |
------------------------------------------
我该怎么做?
答案 0 :(得分:0)
我正在寻找一个现成的函数来从数组生成这样一个字母列表,并在带有索引字母的表中显示这样的列表,如下所示:
由于我找不到一个我写过的,我在这里发帖供所有人使用:
function alphaTable($array,$columns=NULL) {
$i = 0;
$index_css_style_name = 'alphaindex';
$entry_css_style_name = 'alphaentry';
sort($array); // sort our array alphabetically
$list = array(); // create empty array which will contain the alphabetic index list
while ( $i < count($array) ) { // cycle through our array
$index[$i] = substr($array[$i],0,1); // get first character of entry
if ( $i == 0 && is_numeric($index[$i]) ) {
$list[] = ' <div class="'.$index_css_style_name.'">[0-9]</div>'."\n"; // add the default index for numbers/digits
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
} else if ( $i > 0 && !is_numeric($index[$i]) && $index[$i] != $index[($i - 1)] ) { // if it is not numeric then it's a letter of the alphabet
$list[] = ' <div class="'.$index_css_style_name.'">'.strtoupper($index[$i]).'</div>'."\n"; // add the uppercase letter of the current index
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
} else {
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
}
$i++;
}
unset($i);
// check if the function calls specifies a numnber of desired columns for the table
if ( !isset($columns) )
$columns = 4; // if number of columns is not specified, let's set it to 4
$epc = count($list) / $columns; // get the entries per columns
$epc = ceil($epc); // round it up!!
$i = 1; // let's start at 1 so when we multiply by 0 it doesn't return 0
$e = 0;
$table = "\n".'<table border=1>'."\n";
$table .= ' <tr valign="top">'."\n";
while ( $i <= $columns ) { // less or equal to (because we started at 1)
$table .= ' <td>'."\n";
while ( $e < ($epc * $i) ) { // we increment e within the i while loop so that we can continue with the entries in the table
if ( !empty($list[$e]) )
if ( substr_count($list[$e],$index_css_style_name) > 0 ) // to prevent double <span> tags we check whether our desired index css styling is present
$table .= $list[$e]; // if it's an index we just add it to the table
else
$table .= ' <span class="'.$entry_css_style_name.'">- '.$list[$e].'</span>'."\n"; // if it's an entry we style it and add it to the table
$e++;
}
$table .= ' </td>'."\n";
$i++;
}
$table .= ' </tr>'."\n";
$table .= '</table>'."\n";
unset($i);
unset($e);
return $table;
}
当我被困在某事上时,试图回馈给我这么多帮助过的社区。 随意使用。 不客气; - )