2011-07-09 130 views
0

美好的一天。顯示陣列

我在五列中顯示數組,我需要將值推到最後,如果具有指定鍵的值最後到達。

<?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>&nbsp;</td>"; 
        } 
      print "</tr></table>"; 
    } 
    } 
    ?> 

我用這個代碼基於下面的評論中五列

+2

什麼錯誤? – rackemup420

+0

我沒有任何錯誤。實際上我不想在每一行的末尾顯示這兩個值。在這種情況下,該值之前的值必須被推到末尾 – jeni

回答

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 . '">&nbsp;</td>'; 

    echo '</tr>'; 
    } 

    echo '</table>'; 
} 
+0

實際上我不想在每行末尾顯示索引值。如果索引值到達行的末尾,索引值之前的值必須像末尾一樣推入。 '1 2 3 5 6 4' – jeni

+0

@jeni - 「索引」是什麼意思? –

+0

「m」=>「5」,「s」=>「6」索引值 – jeni