→ 在有任何答案之前已经开始了这个,即使已经有可以接受的答案,也决定完成它。这个版本更加动态,并且对表格的样式进行了一些自定义:
→代码:
/* Arrays from Question */ $a1 = array( 'a' => 1, 'b' => 2, 'c' => 3 ); $a2 = array( 'a' => 4, 'b' => 5, 'd' => 6 ); $a3 = array( 'a' => 7, 'c' => 8, 'd' => 9, 'x' => 10 );
/* Process Arrays */ $result = handle_arrays( $a1, $a2, $a3 );
/* Create & Echo Table */ echo ( array_table( $result ) );
function handle_arrays() {
/* Get Arrays */ $params = func_get_args(); $result = array();
/* Merge Arrays */ foreach( $params as $k=>$v ) { foreach( $v as $key=>$val ) { if( !array_key_exists( $key, $result ) ) $result[ $key ] = array(); $result[ $key ][ $k ] = $val; } }
/* Handle Blanks */ for( $x = 0; $x < func_num_args(); $x++ ) { foreach( $result as $key=>$val ) { if( !array_key_exists( $x, $val ) ) { $result[ $key ][ $x ] = '-'; } ksort( $result[ $key ] ); } }
/* Return Array */ $return = array( func_num_args(), $result );
return( $return );
}
function array_table( $array ) {
/* Array # & Result Array */ $n = $array[ 0 ]; $a = $array[ 1 ];
/* Style & Class Control */ $padding_left = 10; $padding_right = 10; $col_align = "center"; $key_align = "left"; $table_class = ""; $col_class = ""; $row_class = ""; $field_class = "";
/* Table & Column Headers */ $html = "<table class='{$table_class}'><tr><td style='padding-right:{$padding_right}px'></td>"; for( $x=0; $x<$n; $x++ ) { $html .= "<td style='padding-left:{$padding_left}px;padding-right:{$padding_right}px' class='{$col_class}'>col-$x</td>"; } $html .= "</tr>";
/* Row and Fields Values */ foreach( $a as $key=>$val ) { $html .= "<tr><td align='{$key_align}' class='{$row_class}'>$key</td>"; foreach( $val as $k=>$v ) { $html .= "<td align='{$col_align}' class='{$field_class}'>$v</td>"; } $html .= "</tr>"; } $html .= "</table>";
return( $html );
}
→输出:
col-0 col-1 col-2
a 1 4 7
b 2 5 -
c 3 - 8
d - 6 9
x - - 10