我看到很多PHP代码都有值和数组在这里和那里传递,有时候,正好在中间,我看到了$someVar = array();.你什么时候array()在PHP中使用,如果你已经可以传递数组,我认为这应该是PHP的优点之一.
参考PHP手册,例1:
http://php.net/manual/en/functions.arguments.php
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
Run Code Online (Sandbox Code Playgroud)
然后从另一个网站的其他地方:
/**
* Model for accessing schedule table
*
* @author Chris Hartjes
*/
class Schedule extends AppModel
{
var $name = 'Schedule';
var $useTable = 'sched2007';
var $useDbConfig = 'stats';
function get($week) {
$scheduledGames = array();
$team = array("a01" => "BUF", "a02" => "COU", "a03" => "HAG", "a04" => "TRI",
"a05" => "BOW", "a06" => "MCM", "a07" => "PHI", "a08" => "WMS",
"a09" => "LAW", "a10" => "PAD", "a11" => "POR", "a12" => "STL",
"n01" => "CSP", "n02" => "COL", "n03" => "MIN", "n04" => "SDQ",
"n05" => "BUZ", "n06" => "CAJ", "n07" => "DTR", "n08" => "SCS",
"n09" => "CRE", "n10" => "MAD", "n11" => "SEA", "n12" => "SPO");
$results = $this->findAll("home LIKE 'a%' AND week = " . (int)$week);
$data = array();
foreach ($results as $result) {
$home = $team[$result['Schedule']['home']];
$away = $team[$result['Schedule']['away']];
$data[$home] = array('home' => $home, 'away' => $away);
}
asort($data);
foreach ($data as $home => $matchup) {
$scheduledGames[$home] = $matchup;
}
$results = $this->findAll("home LIKE 'n%' AND week = " . (int)$week);
$data = array();
foreach ($results as $result) {
$home = $team[$result['Schedule']['home']];
$away = $team[$result['Schedule']['away']];
$data[$home] = array('home' => $home, 'away' => $away);
}
asort($data);
foreach ($data as $home => $matchup) {
$scheduledGames[$home] = $matchup;
}
return $scheduledGames;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里$scheduledGames你有array(),然后$team只是动态显示它的数组,然后$data再次有array().
然而,正如评论中所指出的那样,冒着成为笨蛋的风险,我相信我会把它与隐式数组混淆,所以当它的一个键被赋予某些东西时,是否在PHP中隐式创建数组?
如果你可以传递数组,那意味着你需要一些方法来创建数组,对吗?就是这样array(),它是创建数组的语言构造.
这种代码只是最佳实践:
$foo = array();
foreach ($bar as $baz) {
$foo[] = $baz;
}
return $foo;
Run Code Online (Sandbox Code Playgroud)
如果$bar是空的怎么办?然后循环不会运行.如果$foo在循环之前没有初始化为数组,则循环后它将不存在.在这种情况下return $foo会抛出一个错误,因为你试图返回一些不存在的东西.因此,您始终初始化您要处理的变量.这就是你在几乎所有语言中所做的事情.
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |