displaying array
Good day.
Am displaying array in five columns and I need to push value to the last if values having specified key arrived at last.
<?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>";
开发者_如何学Python }
print "</tr></table>";
}
}
?>
I used this code to display in five columns
Based on the comments below, this should solve your problem:
<?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>';
}
精彩评论