3

我有这段代码可以将任何数组转换为文本表,它几乎可以完美运行,如果您发现任何错误,请告诉我..

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

4 回答 4

4

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

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");
}
于 2010-12-22T04:36:06.813 回答
2

应该是您正在寻找的。您将需要编写一个函数以将 GET 参数作为行传递给 ArrayToTextTable 函数,但它会起作用。

于 2010-12-22T01:33:13.970 回答
0

在下面链接的 URL 中有一些代码可以做到这一点。

样本输出:

│        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

于 2014-05-21T06:22:33.000 回答
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     
于 2020-09-08T14:15:14.877 回答