© 华仔同学

Powered by LOFTER

将一个二维数组以表格的形式显示


    /** 将一个二维数组以表格的形式显示(设计用于将 mysql select 查询出来的二维数组数据以表格形式呈现)
      * @ param array $input        二维数组
      * @ param mixed $field = true    显示第二维的键名集合,如果传入的类型是 array 则输出给定的字段集合 
      * @ param string $cation = '' 自定义表格标题
      * 返回值 string $table HTML表格的字符串
      */

    function arrayToTable( $input, $field = true, $caption = '' ){
        
        $table .= '<table width="100%" border="1" cellspacing="0" cellpadding="0">';
        
        if( !empty( $caption ) )
        {    // 显示标题
            $table .= '<caption>' . $caption . '</caption>';
        }
        
        foreach( $input as $key => $value )
        {    
            if( $field )
            {    // 显示字段
                if( is_bool( $field ) )
                {    // 为 true 时 $ield 赋值为原数组 $input 第二维的键名组成的数组
                    $field = array_keys( $value );
                }
                
                if( is_array($field) )    
                {    // 遍历 $field 数组,输出字段名
                    $table .= '<tr>';
                    foreach( $field as $v ){
                        $table .= '<th>' . $v . '</th>';
                    }
                    $table .= '</tr>';
                }    
                
                $field = false;
            }
            
            $table .= '<tr>';
            foreach( $value as $k => $v )
            {    // 遍历数据
                $table .= '<td>' . $v . '</td>';
            }
            $table .= '</tr>';
        }
        
        $table .= '</table>';
        
        return $table;
    }

发表于2013-10-19.1热度.