PHP: Direct access to an element in an array of objects - php

I am trying to output a set of data, and I have, due to my LEFT OUTER JOIN got multiple rows per match.
I'm using a positive look ahead to see if the next row is the same id as the first. However the return from the database class returns an array of objects.
array(7) {
[0]=> object(stdClass)#4 (8) {
["dom_id"]=>string(1) "3"
["domain"]=>string(11) "example.com"
["status"]=>string(7) "Invalid"
["expiry"]=>string(10) "2010-07-20"
["remaining"]=>string(6) "0 Days"
["rem_id"]=>NULL
["alert_type"]=>NULL
["contact"]=>NULL
}
//etc
I am getting the following error, Fatal error: Cannot use object of type stdClass as array
My code is as follows,
echo $domains[$k+1]->alert_type;
I know that I could assign the new dimension to a variable and access that as an object, but for the sake of neatness I'd rather access it directly.
Is this possible? ..and if it is, how do I approach it?
Ta

Either
fetch as array instead of stdClass or
typecast to (array) or
use a custom class that implements ArrayAccess.

Assuming that $domains is your stdClass object which you wish was an array, you could try using variable variables:
echo $domains->{$k+1}->alert_type;
The real problem though is that you have a bunch of stdClass objects. Are you storing these in a session and then reading them later, or are you neglecting to include a file or something... ?

Related

Uncaught Error: Cannot use object of type stdClass as array

Fatal error: Uncaught Error: Cannot use object of type stdClass as array
$code = json_decode($src);
echo $code["items"];
var_dump shows the following (truncated):
object(stdClass)#7 (3) { ... }
I don't know what stdClass is and how to use it.
Edit:
stdClass is a class which creates an instance of simple object. Properties of classes are to be accessed using ->, not [...] notation.
As per documentation for json_decode, simply setting the second argument to true will result in the result being associative array, which can be in turn accessed like an array.
At the time of posting this question, I didn't try searching on how to decode JSON - as that's pretty simple and I got that working. I was just getting another error (above), and had no luck searching on how to fix that. I believe people have similar problems, as this question is getting some views as well.
Use json_decode($src, true) to get associative array.
This is preferred way, as currently you get mixed arrays and objects and you may end up in crazy house, trying to work with these :)
Alternatively use -> operator to get properties of object.
Currently your item is at:
$code->items[0]->pagemap->cse_image[0]->src
The json_decode function has a second parameter dedicated to just that: setting it to true will return an associative array where there is an object (in { "curly": "braces" }) in JSON.
To illustrate that:
$a = json_decode('{ "b": 1 }', false);
var_dump($a->b);
// prints: int(1)
$a = json_decode('{ "b": 1 }', true);
var_dump($a['b']);
// prints: int(1)
Note the difference in how values are accessed.
Further reading: http://php.net/json_decode

Get value of keys in object in array?

I am someone who has been trying out webdesign for around 2 months now and I have a question. So I have the following array with object:
array(1) {
[0]=>
object(WP_Post)#416 (24) {
["ID"]=>
int(36)
["post_title"]=>
string(7) "Bakuman"
}
I am trying to get the value of "ID", but am not sure how to go about referencing it.
I have tried [0]["ID"], but doesn't work.
Also: Is it possible to get the ID without mentioning the #416 number?
Tried searching for answer, but keep coming up with results that have large amounts of OOP with so much info I can't filter through to what I need. Can anyone hlpe me out?
PHP uses -> for object properties.
So in your case
echo $array[0]->ID;
should output 36
where [0] is the first element of $array which contains the WP_Post object and ID is the property containing the value you're looking for
The 0th element of your array is in fact an object, so to access its properties, you need to use the object referencing operator ->.
Try this: $array[0]->ID

Cant get value in PHP array but var_dump shows that it exists

Long time, my PHP-application ran on a linux server with apache and PHP.
Now I've set up a windows server with apache and php and simple PHP-Programs have problems.
var_dump($data);
die(var_dump($data['a']));
results in
object(stdClass)#1 (1) { ["a"]=> string(1) "b" }
Fatal error: Cannot use object of type stdClass as array in BLUB.php on line 14
var_dump says there is an index a. Why does $data['a'] throw an exception?
EDIT: $data is json_decode($something);
Because its an object, not an array. You cant access it like that. This would be correct:
$data->a;
The error contains your answer - $data is actually an object of type stdClass. You could either:
a) access the property 'a' with $data->a
or
b) typecast $data as an array using (array)$data
You should use:
$data = json_decode($something, true);
To get array from json
As the error says $data is an object, not an array. As such, you want to use object access, rather than array access. In this case, that would be var_dump($data->a)
since $data in an object you have to access it this way:
$data->a;
Otherwise, you can typecast it to an array and access it actually like an array
$dataArr = (array) $data;
$dataArr['a'];
NOTE
This is possible only whether your object attributes are public

Cannot use object of type book as array

I have a PHP class called "book": I've made various instances of it and placed them in an array called $books. I know this is not the best approach in PHP but I've learned OOP in JavaScript and that's how I usually do this.
var_dump of $books will produce
array(2) { [0]=> object(book)#3 (6) { // some properties }
[1]=> object(book)#4 (6) { // some properties } }
I've always been able to iterate in array of objects with foreach($books as $book) but this time I get the error:
Cannot use object of type book as array
Var dump says it is an array: error reporting says is an object. Why is this?
$books is created with $books = array(); and objects inside of it are added with array_push(). $books IS an array and not an object: is PHP crazy?
Your issue looks as you are trying to iterate a Book object instead of an array of Book objects, check well your array and vars; probably your are assigning an object to your array var instead append it to your array
Are you sure $books is an array? It looks like you're trying to iterate over a book object.
There is no $books.length notation in PHP. If anything it should be $books->length but since $books is an array it's count($books). Arrays are not Objects in PHP, unlike JavaScript.

A strange PHP object

I'm using SimpleXML to get some data from an API. Its returning things in this format:
object(SimpleXMLElement)#10 (1) {
[0]=>
string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
My question is, how can I possibly access the string value of this object? If I try to do $myVariable->0 that gives me an error. Doing $zero = '0' and then echo $myVariable->$zero doesn't work either, nor does (array) $myVariable work (that gives a warning).
The trick is that SimpleXMLElement has __toString magic method implemented that would return your string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", so to get this string you just cast (string) on your SimpleXMLElement object:
(string)$myVariable
With PHP you can
print $myVariable;
of course, so explicit (string) here is not necessarily needed.
AFAIR it's like this:
$myVariable->{0}
Edit: That would work in majority of cases, but not this one. It looks like SimpleXML implements not only __toString method like Nemoden pointed out, but also __get, so that accessing object properties in this way results in cloned object being returned.

Categories