【发布时间】:2014-08-25 15:16:06
【问题描述】:
我见过很多 PHP 代码,它们的值和数组在这里和那里传递,有时,在中间,我看到 $someVar = array();。你什么时候在PHP中使用array(),如果你已经可以传递数组,我认为这应该是PHP的优势之一。
以PHP手册为例:
http://php.net/manual/en/functions.arguments.php
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
然后从其他地方another site:
/**
* 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;
}
}
在$scheduledGames 中,您有array(),然后$team 只是动态地显示该数组,然后$data 再次有array()。
然而,正如评论中指出的那样,我认为我将这与隐式数组混淆了,所以Are arrays implicitly created in PHP when one of its keys are assigned something?
【问题讨论】:
-
当您需要创建数组时,您在 PHP 中使用
array().... -
$team 上面没有声明为 Array(),或者至少我能找到。
-
这是一个非常具体的问题。不知道为什么它会被否决。
-
$team = array("a01" => "BUF.....);没有将 $team 定义为数组的哪一部分是您遗漏的?见PHP docs -
你能用
$foo[] = "bar";创建一个数组吗?是的。你应该?不!简单