繁体   English   中英

PHP 添加到 JSON 阵列 - “非法偏移类型”

[英]PHP Adding to JSON Array - “Illegal offset type”

我有一些 arrays:

$officers$dates

每个$officers有两个 arrays ( $i是官员编号):

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

这些分别是(如果$i=0 ):

$raw_tot_data_0 & $raw_pd_data_0

现在我目前有一个JSON数组( $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++;
}

这将返回错误说明

非法偏移类型

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

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

我怎样才能纠正这个工作?

你在这里的价值...

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

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

$tmp = 'officer_'.$i;

暂无
暂无

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

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