Reputation: 147
This is my object:
$reportdata = stdClass Object
(
[1] => stdClass Object
(
[reportname] => reportname1
[reportviews] => 20
[reportpath] => reports/reportname1
[thumbnailurl] => reports/thumbnailurl/thumbnailurl1.jpg
[description] => Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
)
[2] => stdClass Object
(
[reportname] => reportname2
[reportviews] => 20
[reportpath] => reports/reportname2
[thumbnailurl] => reports/thumbnailurl/thumbnailurl2.jpg
[description] => Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
)
)
I am trying to access the individual values using $reportdata[1]['reportviews']
but I get an error
"Cannot use object of type stdClass as array".
How can I access reportname
and reportviews
?
Upvotes: 2
Views: 3872
Reputation: 7753
The way you trying to access an element:
$reportdata[1]['reportviews']
suggest that the main object is an associate array. This code would work if your object is declare like below:
$reportdata = array(
'1' => array (
'reportname' => 'reportname1',
'reportviews' => '20',
'reportpath' => 'reports/reportname1',
'thumbnailurl' => 'reports/thumbnailurl/thumbnailurl1.jpg',
'description' => 'Lorem ipsum dolor.'
),
:
);
But when the stdClass Object
is used, you can access an object property named in a variable as below:
$atr1 = '1'; $atr2 = 'reportviews';
print $reportdata->$atr1->$atr2;
Or using an expression notation:
print $reportdata{'1'}{'reportviews'};
Upvotes: 0
Reputation: 1126
You can access the properties of the object like others have mentioned but wanted to give an alternative option.
get_object_vars — Gets the properties of the given object
array get_object_vars ( object $object )
http://php.net/manual/en/function.get-object-vars.php
$arrReportData = get_object_vars($reportdata);
echo $arrReportData[1]->reportviews;
Note that this is non-recursive, so in your case you'll get an array of objects.
Upvotes: 0
Reputation: 4894
Try like this
$reportdata=json_decode(json_encode($reportdata),true);
then use this
$reportdata[1]['reportviews']
You will not get any error.
Upvotes: 1