Cannot access PHP Object as Array - php

I am facing a strange problem. It may just be a silly mistake, and I am just missing some basics.
I'm running php 5.6.1 on MAMP.
I have a simple array which I get from a mysql query. Using a foreach loop, I can print_r() each value, which gives me: stdClass Object ( [srno] => 6 [link] => this-is-link )
Now I can echo $obj->srno, and that prints fine. But I can't use echo $obj['srno'] which I was previously using, on an older version of PHP, but- It shows nothing.
Any help really appreciated. Thanks!

If you have a stdClass object and need to address it as an array, you can cast it to array quite easily:
$someObj = new stdClass();
$someObj->foo = "bar";
$someArray = (array)$someObj; // Cast the object to an array
echo $someArray['foo']; // Will give you "bar"
Working example: http://3v4l.org/nni1Y
Of course as comments already pointed out, you may want to look at retrieving your mysql results as an array in the first place.

As you said your results return as an object so you can use it by using
$obj->your_field_name to display field value. But your can not use by $obj['field_name'];

Related

How to access properties of a nested PHP object?

I'm trying to do an web app which people can see their status in League of Legends, but I don't even know how to do some things. I've got this class:
stdClass Object
(
[player] => stdClass Object
(
[id] => xxxxxx
[name] => yyyy
[profileIconId] => 627
[summonerLevel] => 30
[revisionDate] => 1422798145000
)
)
and im using this php code:
<?php
$summoner = 'yohanbdo';
$summonerdata = $leagueclass->getsummoner($summoner);
?>
I want to take only the id, name and profileIconId and show it. I don't know how to do this.
PD: My english isn't that good so thanks you all for the edits.
Weird, I was just looking that Riot API a little while ago.
I feel like you're pretty new to this type of notation, so I'll try and be quick but concise with my explanation.
What you have there, as Gerifield stated, are objects. You access their properties by using the -> operator. For example, if I assume that the object $main is what you're var_dumping out, then you could simply get the objects like so:
$main = json_decode($some_json_string);
//Now that we have the object set, we can deal with the properties.
echo $main->player->name;
//This will output the player name.
echo $main->player->id;
//Will output the player ID.
Notice in each case that since the player key of the $main object is also an object, it's properties must be accessed via the -> operator.
However, you could also simply use associative arrays by passing the second parameter to json_decode, like so:
$main = json_decode($some_json_string,TRUE);
echo $main['player']['id'];
echo $main['player']['name'];
Hopefully this helps.

MongoDB unexpected query result

So I'm learning MongoDB and everything was working fine until I wanted to query and discovered that it returns an array that does not work the way I'm used to. Take the example:
$cursor = $collection->find(array('game' => 'Borderlands 2'));
$array = iterator_to_array($cursor);
So far so good, but then I wanted to get a single value to add dynamically to a page:
The game is: <?php echo $array['game'] ?>
And only errors followed. I tried tons of things but then I var_dump it and found that the array is contained under a ID/index array, so this worked:
<?php echo $array["5138225097777c4014000001"]["game"] ?>
I couldn't find any explanation around. Though I understand now how it works, I'm not sure if this is a mistake I made when adding the values to the collection or if I'm missing something. Thanks!!
This is because find returns an array of results(and each result is converted to an array). Hence you have an array of results with the Mongo ObjectId as the key in the array. Use findOne if you want to get just one result.
$cursor = $collection->find(array('game' => 'Borderlands 2'));
while ($document = $cursor->getNext()){
echo $document['game'];
}

Basic PHP - Getting Data Out of an stdClass Object

I have a quick question about something I imagine must be pretty easy - I've done a little research and found some links that seem promising, especially this, but it doesn't work for me for some reason.
Anyway, I made a stored procedure in MySQL and tested it with MySQL Workbench, and it works - it just adds num1 and num2 and returns the result. Now I'm trying to get it to work in PHP, but the result, instead of being an integer, is an array of one stdClass Object which contains that integer. That makes sense from the point of view of procedures that return a lot of data, but I'm having some trouble getting down to just the integer.
I run this:
CALL database.routine(2,7)
And I save the results into $var. When I run print_r($var), I get:
Array
(
[0] => stdClass Object
(
[num1+num2] => 9
)
)
So, to get past the Array part, I specifically asked for the first element in it, by running print_r($var[0]), which gets me:
stdClass Object
(
[num1+num2] => 9
)
And now I need to go one level deeper...I tried what the page I linked to above said and attempted to get to $var[0]->[num1+num2], as the field appears to be named, but that doesn't work. I've also tried a few combinations of single quotes and double quotes, but no luck. How do I get the number 9 out of this object?
Try...
$var[0]->{'num1+num2'}
Try this
$var[0]->{"num1+num2"}
or
$prop = 'num1+num2';
$var[0]->$prop;
Did you try this?
$var[0]->{'num1+num2'}
Try the following $var[0]->{'num1+num2'}
This is crazy but it might just work!
$var[0]->{'num1+num2'}

drupal---the taxonomy array

when i print "print_r($node)" in the node.tpl.php. i get this.
taxonomy] => Array (
[1] => stdClass object (
[tid] =>1
[vid]=>1
[name]=>cms
............)
)
so from the above, I know the taxonomy is an array. the array's value is an object. That the question comes. I looked up the php manual again and again, didn't find there is a saying "the array's value can be a object" why,I can't follow the above's code well. Hope someone can explain it to me. Thank you.
What Pekka write:
echo $node["taxonomy"][1]->tid;
Is not wrong, in the sense that it works for the above example. However, since you are doing this in the node.tpl.php you probably want something more robust, than this, since it only works for nodes with the term that has id 1.
Since the array of taxonomy terms is of the format:
array(tid => term_object)
You need to know the tid to access the term object. If you however want the tid, you can just get the array key:
$tids = array_keys($node["taxonomy"]);
Now, you don't know if or how many terms there is associated to your node, as it can be changed via settings, if you did:
if (!empty($node["taxonomy"])) {
$tids = array_keys($node["taxonomy"]);
$tid = tids[0];
}
You would get the tid of the first term (the one with the lowest tid). If you know from your setup that the node can only have 1 term and since the theme you're doing this in is site specific, this will be good enough for you. Else $tids will be an array of all the tids for the node that you use for your wishes.
in other words, in php, the array's value can be anything. am i right.
Yes, an array can hold values of any data type.
how the code i should write
The "path" to access the variable you show above would be:
echo $node["taxonomy"][1]->tid;

Array call from key not working correctly

I'm trying to call to a specific part of an array with the key # and it's not working. I can output the array and see it...
Array
(
[6] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[7] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[8] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
)
This array is $emailDB. I can call to the array manually with $emailDB[7] and it works, but if my call is dynamic like this it won't work...
<?php
$value = 7;
print_r($emailDB[$value]);
?>
I've never had an issue like this with an array so it's very odd. What really sucks is I'm under deadline with a form not working on a client's site...joy.
We tried this with no luck...
<?php
$value = 7;
print_r($emailDB[intval($value)]);
?>
I thought intval() would assist but it did not.
You're post implies a bug in php itself, which I highly doubt. What's more likely is that what you posted doesn't properly represent the code you're running.
Why don't try this. Make a brand new empty php file. Hardcode the array keys and values and assign them to the $emailDB variable, and then try
$value = 7;
print_r($emailDB[$value]);
You will see you don't have the problem that you claim. You have now started the debugging process, and now you can look at the working, and non working code to compare the difference.
Well, you are echoing an Array, which I assume is printing "Array" onto your screen. If you want to echo the actual contents of the array, you need to use print_r($array) or echo print_r($array, true). You can also try putting the value in quotes, like $emailDB["{$value}"] to see if that works, I sometimes have troubles with integers not going into things properly.
I agree with you all. It had to have been something whacky with how we were pulling in the data somehow. It was a tab-separated file we were exploding. I just re-wrote the whole thing entirely and imported the data into MySQL and all was well.
In hindsight, I have a sneaking suspicion it was a trim() command that was needed and likely nothing more. Dang it...too late, but I learned something about checking over the code for those types of things.

Categories