PHP 是否有与 Python 的列表理解语法等效的语法?
Python 具有语法上不错的列表理解:
S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
在 PHP 中,我需要做一些循环:
$output = array();
$Nums = range(0,9);
foreach ($Nums as $num)
{
$out[] = $num*=$num;
}
print_r($out);
以获取:
数组 ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )
是否有办法在 PHP 中获得类似的列表理解语法? 无论如何,是否可以使用 PHP 5.3 中的任何新功能来实现这一点?
谢谢!
Python has syntactically sweet list comprehensions:
S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In PHP I would need to do some looping:
$output = array();
$Nums = range(0,9);
foreach ($Nums as $num)
{
$out[] = $num*=$num;
}
print_r($out);
to get:
Array
(
[0] => 0
[1] => 1
[2] => 4
[3] => 9
[4] => 16
[5] => 25
[6] => 36
[7] => 49
[8] => 64
[9] => 81
)
Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 .NET 中,相当于 Python 的“语法上甜蜜的列表推导式”的是 LINQ。 在 PHP 中,它有多个端口,包括 YaLinqo 库*。 从语法上讲,它更接近 SQL,而不是使用
for
和if
的传统构造序列,但在功能上,它是相似的:这会生成一个可以输出到控制台的迭代器:
或使用
foreach
进行迭代:这里,
'$v * $v'
是function ($v) { return $v * $v; 的快捷方式; 该库支持该库。 不幸的是,PHP 不支持闭包的短语法,但是这样的“字符串 lambda”可以用来使代码更短。
还有更多方法,从
where
(if
等效)开始,到groupJoin
结束,执行分组连接转换。* 由我开发
In .NET, the equivalent of Python's "syntactically sweet list comprehensions" is LINQ. And in PHP, there're several ports of it, including YaLinqo library*. Syntactically, it's closer to SQL rather than a sequence of traditional constructs with
for
andif
, but functionally, it's similar:This produces an iterator which can either be output to console:
or iterated over using
foreach
:Here,
'$v * $v'
is a shortcut forfunction ($v) { return $v * $v; }
which this library supports. Unfortunately, PHP doesn't support short syntax for closures, but such "string lambdas" can be used to make the code shorter.There're many more methods, starting with
where
(if
equivalent) and ending withgroupJoin
which performs joining transformation with grouping.* developed by me
不是开箱即用的,但请看一下:
http://code.google.com/p/php-lc/ 或http://code.google.com/p/phparrayplus/
not out of the box, but take a look at:
http://code.google.com/p/php-lc/ or http://code.google.com/p/phparrayplus/
从 PHP 7.4 开始,您还可以使用箭头函数 在
array_map
中:观看直播
Since PHP 7.4 you can also use arrow functions in
array_map
:See live
也许是这样的?
这适用于 PHP 5.3+,在旧版本中,您必须单独定义 array_map 的回调
Maybe something like this?
This will work in PHP 5.3+, in an older version you'd have to define the callback for array_map separately
PHP 5.5 可能支持列表推导式 - 请参阅邮件列表公告:
进一步讨论:
PHP 5.5 may support list comprehensions - see the mailing list announcement:
And further discussion: