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中的任何新功能吗?
谢谢!
4 回答
也许是这样的?
这将在PHP 5.3中运行,在旧版本中,您必须单独定义array_map的回调
PHP 5.5可能支持列表推导 - 请参阅邮件列表公告:
并进一步讨论:
What Generators Can Do For You(由ircmaxell提供; 2012年7月23日) - 有斐波那契的例子 .
What PHP 5.5 might look like(作者:NikiC; 2012年7月10日)
Request for Comments: Generators(Wiki开始于2012年6月5日)
没有开箱即用,但请看一下:http://code.google.com/p/php-lc/或http://code.google.com/p/phparrayplus/
在.NET中,相当于Python 's 786748 is LINQ. And in PHP, there'的几个端口,包括YaLinqo library * . 从语法上讲,它更接近SQL而不是传统结构的序列
for
和if
,但在功能上,它是相似的:这会生成一个迭代器,可以输出到控制台:
或者使用
foreach
迭代:这里,
'$v * $v'
是此库支持的function ($v) { return $v * $v; }
的快捷方式 . 不幸的是,PHP不支持闭包的短语法,但是可以使用"string lambdas"来缩短代码 .还有更多方法,从
where
(相当于if
)开始,以groupJoin
结束,它通过分组执行连接转换 .*由我开发