我有这个代码,我不知道为什么我会从中得到错误.
if( ! in_array($repeatType, ['monthly', 'weekly', 'daily'])){
// do somehting
}
$monthly = ['two_years' => 26, 'offset_const' => 4, 'add_unite' => 'weeks'];
$weekly = ['two_years' => 52*2, 'offset_const' => 1, 'add_unite' => 'weeks'];
$daily = array('two_years' => 365*2, 'offset_const' => 1, 'add_unite' => 'days');
for ($i=0; $i < $$repeatType['two_years']; $i++) { #<--- here I get the error
// ..... // rest of the code
Run Code Online (Sandbox Code Playgroud)
这是如此奇怪,因为我检查var_dump($$repeatType)
输出,它似乎很好:
array(3){["two_years"]=>int(730)["offset_const"]=>int(1)["add_unite"]=>string(4)"days"}
Run Code Online (Sandbox Code Playgroud)
这是语法限制.PHP正在尝试将数组索引运算符绑定到$ repeatType(这是一个字符串),并且关联键在字符串中无效,从而导致您的问题.
您需要明确指定变量的开始和开始位置,如下所示:
for ($i=0; $i < ${$repeatType}['two_years']; $i++) {}
Run Code Online (Sandbox Code Playgroud)
解决方法是将其分配给临时变量,如下所示:
$selectedRepeatType = $$repeatType;
for ($i=0; $i < $selectedRepeatType['two_years']; $i++) {}
Run Code Online (Sandbox Code Playgroud)