I have an application in Laravel that is taking a chunk of data from the dB and rendering it as JSON. The following line of code is generating the title error:
$decodedData['detail']['is_stem'] = isset($detailData->is_stem) ? $detailData->is_stem : 0;
The error is: Cannot use assign-op operators with string offsets
$decodedData is a larger array that is eventually returned as JSON. It is created thusly:
$decodedData = json_decode($detailData->detail, true);
$detailData is an object that looks like this:
App\CareersDetails Object
(
[connection:protected] => mysql
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 4
[code] => 1234
[title] => StackOverFlow
[category] => My Category
[detail] => "Some details in JSON"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[original:protected] => Array
(
[id] => 7
[code] => 7890
[title] => StackOverFlowRocks
[category] => My Category
[detail] => "Some details in JSON format"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
When I debug using:
print_r($detailData->is_stem);
The system outputs a 1. Hence it is set.
Alternatively, is my $decodedData array at fault?
Update
Thanks to the comments, I noticed my $decodedData is not an array, it is a string.
Hence I dumped
`$detailData->detail`
To my browser page with print_r and ran it via a simple, seperate PHP script:
$payload = "JSON FROM $detailData->detail";
$data = json_decode($payload,true);
$data['detail']['is_stem'] = 1;
print_r($data );
This works. Hence my question is now why does the string dump from print_r work and my Laravel based-app doesn't?
Or, in other words, why is json_decode returning a string in the Laravel App but an Array in the PHP app with the same input?