2

I've looked at other questions/answers but I'm not fully understanding it. Furthermore, I haven't found one asking my exact question.

I have 7 arrays storing the start and end times for a business. My PHP program checks for the current day and matches it with the start end time for that day. So right now I have 7 if statements similar to this:

if (date(l) == 'Sunday') {
   $start = $SundayAccountingHours['start'];
   $end = $SundayAccountingHours['end'];
 }

What I want to do is clean up the code. So maybe I could have something like

$start = ${$today}.AccountingHours['start'];
$end = ${$today}.AccountingHours['end'];

How can I make this work? Using the above example I'm getting this: Parse error: syntax error, unexpected '[' in C:\xampp\htdocs\Dev.php on line 22 where line 22 is $start is defined. I can't take out the stuff in the brackets because THAT'S the information I need to really get to.

If you can't tell, I'm still novice at PHP so any help will be appreciated.

Thanks!

4

3 回答 3

5
if (date(l) == 'Sunday') {
   $start = $SundayAccountingHours['start'];
   $end = $SundayAccountingHours['end'];
 }

首先,在 . 周围加上引号'l'。它正在寻找一个名为 的常量l,但没有发现它把它当作一个字符串。这是非常糟糕的做法(应该发出警告)。

其次,使用多维数组。您无需尝试使用星期几作为变量名的一部分。例如,

$start = $AccountingHours[$today]['start'];

您可能会在以后发现变量变量,这些变量允许您执行您正在尝试的事情,但我强烈建议您避开它们。我认为它们没有单一的实际应用,它们只会导致混乱和错误(咳嗽)。

于 2013-05-22T02:40:44.973 回答
1

如果您必须使用变量变量名称(尽管您真的应该使用多维数组),请尝试类似的方法。

$start = ${$today.'AccountingHours'}['start'];
于 2013-05-22T02:42:30.043 回答
0

数组元素可以被如下变量引用:

$myArray[$myVar]

数组还可以包含其他数组,如下所示:

$myArray = array();
$myArray['a'] = array();
$myArray['a']['b'] = 'foo';
print $myArray['a']['b'];  // prints 'foo'

所以结合这两个概念,你可以创建一个变量引用的多维数组:

$accountingHours = array();
$accountingHours['Sunday'] = array('start' => ..., 'end' => ...);
// ...
$start = $accountingHours[$today]['start'];
于 2013-05-22T02:42:06.603 回答