PHP 是否具有与 Python 的列表理解语法等效的语法? [英] Does PHP have an equivalent to Python's list comprehension syntax?
问题描述
Python 具有语法上甜蜜的列表推导式:
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]
在 PHP 中,我需要做一些循环:
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);
获得:
数组([0] => 0[1] => 1[2] => 4[3] => 9[4] => 16[5] => 25[6] => 36[7] => 49[8] => 64[9] => 81)
Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )
无论如何在PHP中获得类似的列表理解语法?无论如何,是否可以使用 PHP 5.3 中的任何新功能来实现?
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?
谢谢!
推荐答案
也许是这样?
$out=array_map(function($x) {return $x*$x;}, range(0, 9))
这将适用于 PHP 5.3+,在旧版本中,您必须为 array_map 定义回调分开
This will work in PHP 5.3+, in an older version you'd have to define the callback for array_map separately
function sq($x) {return $x*$x;}
$out=array_map('sq', range(0, 9));
这篇关于PHP 是否具有与 Python 的列表理解语法等效的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!