2011-07-09 21 views
0

おはよう。配列を表示

5列に配列を表示していますが、指定されたキーを持つ値が最後に到着した場合、値を最後までプッシュする必要があります。

<?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>"; 
    } 
    } 
    ?> 

私は以下のコメントに基づいて5列

+2

いただきましエラー? – rackemup420

+0

私は間違いなしです。実際には私は各行の最後に2つの値を表示したくないです。その場合、キーを持つその値の前の値は最後にプッシュされなければなりません – 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