0

假设我有这个数组:

$names = array(

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

我想得到它是这样的:

$ php -f names.php

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

3 回答 3

4

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

for($i=0;$i<strlen($name[0]);$i++) {
for($j=0;$j<count($name);$j++) {
    echo $name[$j][$i];
}
echo '<br/>';}
于 2013-09-18T10:47:17.947 回答
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
*/

阅读有关递归的更多信息>>

于 2013-09-18T10:55:50.133 回答
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
)
于 2013-09-18T11:21:33.793 回答