PHP 添加到 JSON 数组 - "Illegal offset type"



我有一些数组:

CCD_ 1&$dates

每个$officers有两个阵列($i是军官编号(:

${'raw_tot_data_'.$i}&${'raw_pd_data_'.$i}

它们分别是(如果$i=0(:

CCD_ 8&$raw_pd_data_0

现在我有一个$officers0阵列($ourData(,它看起来类似于:

//$ourData
[
//$officer_0
{
"code": "cg",
"tots": [],
"pds": []
},
//$officer_1
{
"code": "crg",
"tots": [],
"pds": []
},
//$officer_2
{
"code": "jan",
"tots": [],
"pds": []
},
...

我想填充每个军官totspds。为此,我尝试了以下操作(这是json_encode($ourData)之前的操作(:

$i=0;
foreach($officers as $officer){
$n=0;
foreach($dates as $date){
$tmp = ${'officer_'.$i};
$ourData[$tmp]['tots'][$n] = (    //error here
$date.' : '.${'raw_tot_data_'.$i}[$n]
);
$ourData[$tmp]['pds'][$n] = (    //error here
$date.' : '. ${'raw_pd_data_'.$i}[$n]
);
$n++;
}
$i++;
}

这会返回错误,说明

非法偏移类型

经过一些研究,我发现了这一点:

当您尝试使用对象或数组作为索引键来访问数组索引时,会发生非法偏移类型错误。

我该如何更正才能工作?

您在这里的价值。。。

$tmp = ${'officer_'.$i};

$tmp设置为变量的值,当(我认为(您希望它只是字符串本身时。。。

$tmp = 'officer_'.$i;

最新更新