简体   繁体   中英

PHP Adding to JSON Array - “Illegal offset type”

I have some arrays:

$officers & $dates

Each $officers has two arrays ( $i being officers number):

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

these respectively being (if $i=0 ):

$raw_tot_data_0 & $raw_pd_data_0

Now I currently have a JSON array ( $ourData ) which looks similar to:

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

I would like to populate each officers tots and pds . To do that I attempted the following (this is pre 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++;
}

This returns errors stating

Illegal offset type

after some research I found this:

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

How could I correct this to work?

Your value here...

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

Is setting $tmp to the value of a variable, when (I think) you want it to be just the string itself...

$tmp = 'officer_'.$i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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