Dar*_*ton 72 php arrays language-comparisons list-comprehension higher-order-functions
Python具有语法上的甜蜜列表理解:
S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Run Code Online (Sandbox Code Playgroud)
在PHP中我需要做一些循环:
$output = array();
$Nums = range(0,9);
foreach ($Nums as $num)
{
$out[] = $num*=$num;
}
print_r($out);
Run Code Online (Sandbox Code Playgroud)
要得到:
数组([0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81)
反正有没有在PHP中获得类似的列表理解语法?无论如何使用PHP 5.3中的任何新功能吗?
谢谢!
Pau*_*xon 81
也许是这样的?
$out=array_map(function($x) {return $x*$x;}, range(0, 9))
Run Code Online (Sandbox Code Playgroud)
这将在PHP 5.3+中运行,在旧版本中,您必须单独定义array_map的回调
function sq($x) {return $x*$x;}
$out=array_map('sq', range(0, 9));
Run Code Online (Sandbox Code Playgroud)
PHP 5.5可能支持列表推导 - 请参阅邮件列表公告:
并进一步讨论:
| 归档时间: |
|
| 查看次数: |
15622 次 |
| 最近记录: |