作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我在某个地方遇到了这个问题,我想知道如何使用 PHP 解决这个问题。鉴于此文本:
$str = '
PHP is a
widely-used
general-purpose
server side
scripting
language
';
如何像下面给出的那样垂直回显文本:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
我会选择更简洁优雅的代码作为答案。
最佳答案
正如其他人已经演示的那样,array_map
能够进行翻转,这基本上是您需要解决的主要问题。剩下的就是你如何安排代码了。我认为你的版本非常好,因为它很容易理解。
如果您更倾向于其他极端情况,请小心处理:
$str = 'PHP is a
widely-used
general-purpose
server side
scripting
language';
$eol = "\n";
$turned = function($str) use ($eol) {
$length = max(
array_map(
'strlen',
$lines = explode($eol, trim($str))
)
);
$each = function($a, $s) use ($length) {
$a[] = str_split(
sprintf("%' {$length}s", $s)
);
return $a;
};
return implode(
$eol,
array_map(
function($v) {
return implode(' ', $v);
},
call_user_func_array(
'array_map',
array_reduce($lines, $each, array(NULL))
)
)
);
};
echo $turned($str), $eol;
给你:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
这修复了另一个不正确的答案的输出(现已修复)。
关于php - 如何在 PHP 中垂直回显文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10784853/
我是一名优秀的程序员,十分优秀!