繁体   English   中英

PHP非法字符串偏移量错误

[英]PHP illegal string offset error

我有这段代码,我不知道为什么会从中得到错误。

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

这太奇怪了,因为我检查了var_dump($$repeatType)输出,看起来很好:

array(3){["two_years"]=>int(730)["offset_const"]=>int(1)["add_unite"]=>string(4)"days"}

这是语法限制。 PHP试图将array-index运算符绑定到$ repeatType(这是一个字符串),并且关联键在字符串中无效,从而引起您的问题。

您需要像这样明确指定变量的开始位置和开始位置:

for ($i=0; $i < ${$repeatType}['two_years']; $i++) {}

一种解决方法是将其分配给如下所示的临时变量:

$selectedRepeatType = $$repeatType;
for ($i=0; $i < $selectedRepeatType['two_years']; $i++) {}

我可以理解您想要的内容,但是这个表达式$$ repeatType ['two_years']模棱两可,至少对我来说,我需要一些时间来运行代码来查找输出内容,所以首先我建议您不要不要使用这样的表达。

好的,回到问题上,您希望$$repeatType['two_years']返回数字26,52 * 2和365 * 2之一。但是让我们运行代码。

$name='a';
$a=array('n'=>1);
$a=array('n'=>2);
$a=array('n'=>3);

var_dump($$name['n']);  //array(1) { ["n"]=> int(3) }
var_dump($$name);       //array(1) { ["n"]=> int(3) }
var_dump(${$name}['n']);//int(3)

好,我们知道发生了什么,您可以在这里找到原因。

从您的代码中,我可以了解到您尚未为$ repeatType ['two_years']设置值。 首先分配一个值

$repeatType['two_years'] = "monthly";

现在,“ $ monthly”是一个数组,因此您可以调用:

for ($i=0; $i < ${$repeatType['two_years']}['two_years']; $i ++){
    //Loop 26 times.
}

需要定义$ repeatType ['two_years'],否则将产生PHP错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM