美好的一天。
我在五列中显示数组,如果指定键的值最后到达,我需要将值推到最后一列。
<?php
$say = array("1","2","3","4","m"=>"5","s"=>"6","7","8","9","10","11","12");
$columns = 5;
for ($p=0; $p <count($say); $p++) {
if ($p==0) {
print "<table><tr>";
} elseif ($p%$columns == 0) {
print "<tr>";
}
print "<td>".htmlspecialchars($say[$p])."</td>";
if (($p+1)%$columns == 0) {
print "</tr>";
}
if ($p==count($say)-1) {
$empty = $columns - (count($say)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
?>
我使用此代码显示在五列
中答案 0 :(得分:3)
根据以下评论,这可以解决您的问题:
<?php
// Returns TRUE is the value is non-numeric otherwise FALSE.
function is_non_numeric($value)
{
return ! is_numeric($value);
}
// The number of columns
$columns = 5;
// The data
$data = array('1', '2', '3', '4', 'm' => '5', 's' => '6', '7', '8', '9', '10', '11', '12');
// Chunk the data into rows of {$columns} columns.
$rows = array_chunk($data, $columns, TRUE);
// Output the table if there are rows.
if ( ! empty($rows) )
{
echo '<table>';
// Loop through each rows.
foreach ( $rows as $row )
{
// Find all non-numeric keys, if any.
$non_numeric_keys = array_filter(array_keys($row), 'is_non_numeric');
// Loop through each non-numeric keys if one or more were found.
if ( ! empty($non_numeric_keys) )
foreach ( $non_numeric_keys as $offset => $non_numeric_key )
{
// Skip this one of the non-numeric key isn't the first or last of the row.
if ( $offset != 0 && $offset != ( $columns - 1 ) )
continue;
// Remove the value with a non-numeric key from the row.
$value = array_splice($row, $offset, 1);
// Randomly select where the value will be re-inserted.
$random = rand(1, ( $columns - 2 ));
// Re-insert the value with a non-numeric key.
array_splice($row, $random, 0, $value);
}
echo '<tr>';
// Loop through each columns.
foreach ( $row as $index => $column )
echo '<td>' . $column . '</td>';
// If the row doesn't have {$columns} columns add one that spans the number of missing columns.
if ( ( $colspan = $columns - count($row) ) != 0 )
echo '<td colspan="' . $colspan . '"> </td>';
echo '</tr>';
}
echo '</table>';
}