2014-11-15 63 views
1

幫助,MYSCRIPT生成動態數組,輸出是這樣這樣的:如何分割動態數組,並將其應用到表

Array 
(
    [0] => A, B, C, D 
    [1] => 15,20,24,19 
    [2] => X,Y,Z,W 
) 

Array 
(
    [0] => A, B, C, D 
    [1] => 15,20,24,19 
) 

這裏是一段2主索引或更多。

如何將它們應用到HTML表格,這樣的結果會是這樣:

------------------ 
Field 1 | Field 2 | 
------------------ 
A  | 15  | 
------------------ 
B  | 20  | 
------------------ 
C  | 24  | 
------------------ 
D  | 19  | 
------------------ 

凡領域是主要指標的後續數。

大感謝您的幫助:)

回答

0

如果他們是用逗號分隔的字符串,那麼你需要映射那些第一和爆炸。然後,您可以繼續對它們進行分組並排列它們,以便它們可以更容易地循環播放。例如:

$array = ['A,B,C,D', '15,20,24,19', 'X,Y,Z,W']; 
// explode comma delimited 
$pieces = array_map(function($piece){ 
    return explode(',', $piece); 
}, $array); 
// group them 
$group = array(); $i = 0; 
while(true) { 
    foreach ($pieces as &$piece) { 
     $group[$i][] = array_shift($piece); 
    } 
    $i++; 
    $last = end($pieces); 
    if(empty($last)) break; 
} 
// then just echo them in a table 
echo '<table cellpadding="10">'; 
echo '<tr>'; 
for($x = 1, $size = count($array); $x <= $size; $x++) echo '<td>Field ' . $x . '</td>'; 
echo '</tr>'; 
foreach ($group as $value) { 
    echo '<tr>'; 
    foreach($value as $v) { 
     echo '<td>' . $v . '</td>'; 
    } 
    echo '</tr>'; 
} 
echo '</table>'; 

Sample Out

+0

一個小東西,在你的'for'行動你繼續計數相同不變'數組$ array'的長度。最好把這個值放在一個「變量」中並重用。 – RST

+0

@RST肯定沒有問題,很容易修改 – Ghost

0

對字符串的每一個子陣列調用explode()後,你將不需要運行任何進一步的準備,只是用array_column()訪問列數據。

代碼:(Demo

$array=['A, B, C, D', '15,20,24,19', 'X,Y,Z,W']; // differing delimiters: comma vs comma-space 
$array=array_map(function($s){return preg_split('/, ?/',$s);},$array); 

echo "<table>"; 
    echo "<tr>"; 
     for($x=1,$column_count=sizeof($array); $x<=$column_count; ++$x){ 
      echo "<th>Field$x</th>"; 
     } 
    echo "</tr>"; 
    foreach($array[0] as $i=>$v){ 
     echo "<tr><td>",implode("</td><td>",array_column($array,$i)),"</td></tr>"; 
    } 
echo "</table>"; 

輸出:

<table> 
    <tr> 
     <th>Field1</th><th>Field2</th><th>Field3</th> 
    </tr> 
    <tr> 
     <td>A</td><td>15</td><td>X</td> 
    </tr> 
    <tr> 
     <td>B</td><td>20</td><td>Y</td> 
    </tr> 
    <tr> 
     <td>C</td><td>24</td><td>Z</td> 
    </tr> 
    <tr> 
     <td>D</td><td>19</td><td>W</td> 
    </tr> 
</table> 
相關問題