将任何数组转换为文本表

时间:2010-12-22 01:27:44

标签: php debugging shop

我有这个代码将任何数组转换成文本表,它几乎完美,如果你发现任何错误请告诉我..

function arr2textTable($table) {
    function clean($var) { 
        $search=array("`((?:https?|ftp)://\S+[[:alnum:]]/?)`si","`((?<!//)(www\.\S+[[:alnum:]]/?))`si");
        $replace=array("<a href=\"$1\" rel=\"nofollow\">$1</a>","<a href=\"http://$1\" rel=\"nofollow\">$1</a>");
        $var = preg_replace($search, $replace, $var);
        return $var;
    }
    foreach ($table AS $row) {
        $cell_count = 0;
        foreach ($row AS $key=>$cell) {
            $cell_length = strlen($cell);
            $key_length = strlen($key);
            $cell_length = $key_length > $cell_length ? $key_length : $cell_length;
            $cell_count++;
            if (!isset($cell_lengths[$key]) || $cell_length > $cell_lengths[$key])
                $cell_lengths[$key] = $cell_length;
        }   
    }
    $bar = "+";
    $header = "|";
    foreach ($cell_lengths AS $fieldname => $length) {
        $bar .= str_pad("", $length+2, "-")."+";
        $name = $fieldname;
        if (strlen($name) > $length) {
            $name = substr($name, 0, $length-1);
        }
        $header .= " ".str_pad($name, $length, " ", STR_PAD_RIGHT) . " |";
    }
    $output = "${bar}\n${header}\n${bar}\n";
    foreach ($table AS $row) {
        $output .= "|";
        foreach ($row AS $key=>$cell) {
            $output .= " ".str_pad($cell, $cell_lengths[$key], " ", STR_PAD_RIGHT) . " |";
        }
        $output .= "\n";
    }
    $output .= $bar."\n";
    return clean($output);
}

$table=json_decode([{"OS":"Debian","Stars":"10","Link":"http://debian.org/"},{"OS":"Linux Mint Debian","Stars":"9","Link":"http://linuxmint.com/"},{"OS":"Fedora","Stars":"9","Link":"http://fedoraproject.org/"}]);
echo arr2textTable($table);

返回:

+-------------------+-------+---------------------------+
| OS                | Stars | Link                      |
+-------------------+-------+---------------------------+
| Debian            | 10    | http://debian.org/        |
| Linux Mint Debian | 9     | http://linuxmint.com/     |
| Fedora            | 9     | http://fedoraproject.org/ |
+-------------------+-------+---------------------------+

4 个答案:

答案 0 :(得分:2)

This应该是你想要的。您需要编写一个函数来将GET参数作为行传递给ArrayToTextTable函数,但它可以工作。

答案 1 :(得分:1)

我已经自我解决了我自己的问题这是新代码:

function arr2textTable($a, $b = array(), $c = 0) {
    $d = array();
    $e = "+";
    $f = "|";
    $g = 0;
    foreach ($a as $h)
        foreach ($h AS $i => $j) {
            $j = substr(str_replace(array("\n","\r","\t","  "), " ", $j), 0, 48);
            $k = strlen($j);
            $l = strlen($i);
            $k = $l > $k ? $l : $k;
            if (!isset($d[$i]) || $k > $d[$i])
                $d[$i] = $k;
        }
    foreach ($d as $m => $h) {
        $e .= str_pad("", $h + 2, "-") . "+";
            if (strlen($m) > $h)
                $m = substr($m, 0, $h - 1);
            $f .= " " . str_pad($m, $h, " ", isset($b[$g]) ? $b[$g] : $c) . " |";
            $g++;
    }
    $n = "{$e}\n{$f}\n{$e}\n";
    foreach ($a as $h) {
        $n .= "|";
        $g = 0;
        foreach ($h as $i => $o) {
            $n .= " " . str_pad($o, $d[$i], " ", isset($b[$g]) ? $b[$g] : $c) . " |";
            $g++;
        }
        $n .= "\n";
    }
    $p = array(
        "`((?:https?|ftp)://\S+[[:alnum:]]/?)`si",
        "`((?<!//)(www\.\S+[[:alnum:]]/?))`si"
    );
    $q = array(
        "<a href=\"$1\" rel=\"nofollow\">$1</a>",
        "<a href=\"http://$1\" rel=\"nofollow\">$1</a>"
    );
    return preg_replace($p, $q, "{$n}{$e}\n");
}

答案 2 :(得分:0)

在下面链接的网址上有一些代码可以做到这一点。

示例输出:

│        ID        │       NAME       │     BALANCE      │     COMMENTS     │
├──────────────────┼──────────────────┼──────────────────┼──────────────────┤
│ 0                │ Joe              │ 1000000          │ This is the firs │
│                  │                  │                  │ t comment.       │
├──────────────────┼──────────────────┼──────────────────┼──────────────────┤
│ 1                │ Jack             │ 500000           │ Lorem ipsum dolo │
│                  │                  │                  │ r sit amet, cons │
│                  │                  │                  │ ectetur adipisci │
│                  │                  │                  │ ng elit. In luct │
│                  │                  │                  │ us pellentesque  │
│                  │                  │                  │ ante, a placerat │
│                  │                  │                  │  purus molestie  │
│                  │                  │                  │ et. Nam urna pur │
│                  │                  │                  │ us, accumsan ege │
│                  │                  │                  │ t dolor consequa │
│                  │                  │                  │ t, ultricies con │
│                  │                  │                  │ vallis nibh.     │
├──────────────────┼──────────────────┼──────────────────┼──────────────────┤
│ 2                │ William          │ 10000            │ This_is_a_very_v │
│                  │                  │                  │ ery_very_very_ve │
│                  │                  │                  │ ry_very_very_ver │
│                  │                  │                  │ y_very_very_very │
│                  │                  │                  │ _long_line_with_ │
│                  │                  │                  │ no_spaces_or_lin │
│                  │                  │                  │ e_breaks         │
├──────────────────┼──────────────────┼──────────────────┼──────────────────┤
│ 3                │ Avrell           │ 200              │ Avrell is the    │
│                  │                  │                  │ (tall|dumb)est   │
│                  │                  │                  │ one.             │
└──────────────────┴──────────────────┴──────────────────┴──────────────────┘

表格宽度(列数)可以调整。

来源:http://opentechnotes.blogspot.com.au/2014/05/display-php-array-as-plaintext-table.html

答案 3 :(得分:0)

我找不到简单的库,所以这是创建纯文本等宽表的简单函数。

我可以确定它的简洁性,但我现在将按原样发布。该代码未注释,因为它很不言自明:

<?php
function array2table($table){
    $maxLengths = array();
    $plainTable = '';
    $tableArray = array();
    $rightPadding = 6;
    
    foreach($table as $rowType => $rows){
        if($rowType != 'rows'){ $rows = array($rows); }
        foreach($rows as $rowNum=>$cols){
            foreach($cols as $i=>$val){
                $length = strlen($val);
                $col = $i+1;
                if(!isset($maxLengths[$col])){ $maxLengths[$col] = 0; }
                if($maxLengths[$col] < $length){
                    $maxLengths[$col] = $length;
                }
                $tableArray[$rowType][$rowNum][] = array($length, $val);
            }
        }
    }
    
    $tableLength = 0-$rightPadding;
    foreach($maxLengths as $l){ $tableLength += $l+6; }
    
    foreach($tableArray as $rowType => $rows){
        if($rowType == 'foot'){
            $plainTable .= PHP_EOL.str_repeat('-', $tableLength);
        }
        
        foreach($rows as $i=>$cols){
            $plainTable .= $plainTable ? PHP_EOL : '';
            foreach($cols as $i=>$col){
                $plainTable .= $col[1].str_pad(' ', ($maxLengths[$i+1]-$col[0])+($i<count($maxLengths)-1?$rightPadding:0));
            }
        }
        
        if($rowType == 'head'){
            $plainTable .= PHP_EOL.str_repeat('=', $tableLength);
        }
    }
    
    return $plainTable;
}
?>

表数组格式为:

//head and foot are optional
$table = array(
    'head' => array('Name', 'Surname', 'Age', 'Tea or Coffee'),
    'rows' => array(
        array('John', 'Doe', '40', 'Coffee'),
        array('John', 'Smith', '40', 'Tea'),
        array('Longname', 'Patterson Junior', '40', 'Tea'),
        array('Home', 'Simpson', '12', 'Duff'),
    ),
    'foot' => array('Ages:', '', '12-40', 'Tea Wins'),
);

以上将输出

Name          Surname               Age        Tea or Coffee 
============================================================
John          Doe                   40         Coffee       
John          Smith                 40         Tea          
Longname      Patterson Junior      40         Tea          
Home          Simpson               12         Duff         
------------------------------------------------------------
Ages:                               12-40      Tea Wins