用PHP垂直打印

时间:2013-09-18 10:42:17

标签: php printing

假设我有这个数组:

$names = array(

    'Abcd',
    'Efgh',
    'Jklm',
);

我想得到这样的东西:

$ php -f names.php

A  E  J
b  f  k
c  g  l
d  h  m
$

3 个答案:

答案 0 :(得分:4)

使用此代码并假设您的数组名称为$ name

for($i=0;$i<strlen($name[0]);$i++) {
for($j=0;$j<count($name);$j++) {
    echo $name[$j][$i];
}
echo '<br/>';}

答案 1 :(得分:2)

这是一个递归功能。如果您希望换行符在HTML中使用,只需将\n更改为<br>

function verticalPrint($arr, $index = 0){
    $out = '';

    //Loop through the array $arr to get each string $str
    foreach($arr as $str){

        //Check if the $str is too short. If so, just save a space.
        //Otherwise, save the character at position $index and prepend a space to it
        if(strlen($str) <= $index)
            $out .= ' ';
        else
            $out .= ' '.substr($str, $index, 1);
    }

    //Remove all spaces in the beginning and the end of the string.
    $out = trim($out);

    //When all spaces in the beginning and the end are removed, is the string empty?
    //If so, we have done all the characters and $out is now finished.
    //If the string isn't empty, there might be more so we return our sting $out and
    //appends another call to this function to the end. Called recursion. This time 
    //with $index+1 so we take the next character.
    if(strlen($out))
        return $out."\n".verticalPrint($arr, $index+1);
    return $out;
}

$names = array(

    'Abcd',
    'Efgh',
    'Jklm',
);

print verticalPrint($names);

//Prints this
/*
A E J
b f k
c g l
d h m
*/

详细了解Recursion >>

答案 2 :(得分:0)

这是一个不仅以你想要的方式打印,而且实际上对数组本身进行转置的那个.......

$names = array('ABCD','EFGH','JKLM');
array_transpose($names);
$names = array('ABCDEF','GHIJKL','MNOPQR','STUVWX');
array_transpose($names);

function array_transpose($arr) {
    $a = count($arr);
    echo "<pre>\n";
    print_r($arr);
    $transarr = [];
    $verty = [];
    $chars = [];
    $i = 0;
    $j = 0;
    foreach ($arr as $i => $ar) {
        $chars = str_split($ar);
        foreach ($chars as $j => $char) {
            $transarr[$j][$i] = $char;
        }
    }
    foreach ($transarr as $j => $trans) {
        $transar = join($trans);
        array_push($verty,$transar);
    }
    print_r($verty);
    echo "</pre>\n";
}

<强>输出

Array
(
    [0] => ABCD
    [1] => EFGH
    [2] => JKLM
)
Array
(
    [0] => AEJ
    [1] => BFK
    [2] => CGL
    [3] => DHM
)
 Array
(
    [0] => ABCDEF
    [1] => GHIJKL
    [2] => MNOPQR
    [3] => STUVWX
)
Array
(
    [0] => AGMS
    [1] => BHNT
    [2] => CIOU
    [3] => DJPV
    [4] => EKQW
    [5] => FLRX
)