How to reference this variable (nested objects/arrays)? - php

I'm learning PHP and Drupal. I need to reference a variable contained in an array called $contexts.
So print_r($contexts) gives me this:
Array (
[context_view_1] => ctools_context Object (
[type] => view
[view] => view Object (
[db_table] => views_view
[result] => Array (
[0] => stdClass Object (
[nid] => 28
[node_data_field_display_field_display_value] => slideshow
)
)
eek confusing. I want to work with the node_data_field_display_field_display_value variable. I think my code needs to be like this, but I know this isn't right:
if ($contexts['context_view_1']['view']['result'][0]
['node_data_field_display_field_display_value'] == 'slideshow') then do whatever...
Thanks!

You suggested the following array reference to get to the variable you want:
$contexts['context_view_1']['view']['result'][0]['node_data_field_display_field_display_value']
The reason this doesn't work is because some of the structures in the chain are actually objects rather than arrays, so you need a different syntax for them to get at their properties.
So the first layer is correct, because $contexts is an array, so context_view_1 is an array element, so you'd get to it with $contexts['context_view_1'] as you did.
But the next level is an object, so to get to view, you need to reference it as an object property with -> syntax, like so: $contexts['context_view_1']->view
For each level down the tree, you need to determine whether it's an object or an array element, and use the correct syntax.
In this case, you'll end up with something that looks like this:
$context['context_view_1']->view->result[0]->node_data_field_display_field_display_value

That's a mess of a variable. The issue you're having is that you're using the bracketed notation, e.g. "['view']", for each "step" in the navigation through your variable. That would be fine if each child of the variable were an array, but not every one is.
You'll note, for example, that $contexts['context_view_1'] is actually an object, not an array (take note that it says "[context_view_1] => ctools_context Object"). Whereas you would use that bracketed notation to address the elements of an array, you use the arrow operator to address the properties of an object.
Thus, you would address the field you are trying to reach with the following expression:
$contexts['context_view_1']->view->result[0]->node_data_field_display_field_display_value

For properties listed as "Object", you need to use -> to get into it, and "Array", you need to use []. So:
$contexts['context_view_1']->view->result[0]->node_data_field_display_field_display_value

$contexts['context_view_1']->view->result[0]->node_data_field_display_field_display_value

echo $context['context_view_1']->view->result[0]->node_data_field_display_field_display_value;

Do not mistake objects with arrays. A memeber of an array can be accesed by $array['member'], but fields of an object can be accessed as $object->fieldname.

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.

PHP API returns an array - need to reuse it in variables

I have a PHP script that dumps data from an API.
The dump is an array
print_r($answer);
outputs
Array ( [success] => 1 [serial] => s001 [url] => http://gooole.com )
I want to have another variable called $url that holds the value url from the array (held in $answer) in PHP.
I'm unfamiliar with this.
check out extract() it will take the keys from an array, and create variable of the same name to store them in. There are a few flags you can pass it, to determine exactly what it does with things like pre-existing variables of the same name.
EDIT: as mentioned in the comments on your question, though, $url = $answer['url']; is probably the simplest way to go.

Accessing specified Element of Array with Twig

I have the following array and i want to access the value of a specified element with twig.
numbers => Array ([01234567] => Array ( [0] => 9876543210 [1] => 8765432109 [2] => 0000000000))
I know there is only one entry in numbers, so I want to access the array with the key 01234567 directly.
Even tough numbers|keys[0] does return the correct key, I can't use it like numbers[numbers|keys[0]] to get the array. I also tried the attribute(array, item) function, but i didn't got it to work.
Is it possible to access it directly or do I need to use loops?
You have found a probably undocumented "feature" of Twig. If you check the source code, twig tries to determine if the given key is numeric, or not. It does this check with the ctype_digit function, which checks if a variable contains only numeric characters.
The example in your question contains an array key, which meets this conditions: it contains only numbers. Unfortunately, it also starts with a zero, which is removed when the string is converted into an integer.
I'm not exactly sure that this is intended behavior, so you may try to report this example as a bug.
For the current twig implementation, because everything except the loop construct uses the getAttribute function, you have no other choice but to use a for loop.

How do I get the value of an object member that has a pipe?

Given this object, how do I output the value of pipe|title?
stdClass Object
(
[profile|title] => John Doe
)
I've never seen a pipe in a member name before.
You can make use of the curly brackets and put the field name in a string:
$obj->{'profile|title'}
You can use
$obj->{'profile|title'}
Since you're just using it as a stupid data store, you can also cast it as an array
$arr = (array) $obj;
$arr['profile|title'];
This would be more useful if you're using a lot of values out of it this way or you need to iterate over it.

How do you use a # symbol in the name of a PHP object

I've got an XML file that has the label #attributes for one of the names
SimpleXMLElement Object
(
[#attributes] => Array
(
[PART_NUMBER] => ABC123
I want to make a reference to this object like $product->#attributes['part_number'] but of course the # symbol causes an error.
So how do I reference this item in the object?
Well, in the case of SimpleXML, you'd call the $product->attributes() method as defined in the manual. That will give you an array mapping attribute names to values.
$obj:
stdClass Object
(
[#id] => Hello
[$] => World!
)
To access #id and $:
echo $obj->{'#id'};
echo ' ';
echo $obj->{'$'};
$product[0]['PART_NUMBER'] should work.
If you got more than one attribute, you should use $product->attributes() in a foreach
attributes in SimpleXML manual
If you're using SimpleXML objects, is already have an attributes method built into it (without the # sign) -- use it like this: $product->attributes('part_number');
If you're trying to create your own objects to map to the XML, then as you already found out, you can't use the # symbol in a PHP variable name (nor any other symbol except underscore).
I'd suggest simply using $product->attributes['part_number'] (ie without the # symbol at all) and mapping it inside your class.
If you really need to map it into your variable names, the best you can really hope for would be some kind of replacement string that you can swap in and out as you convert between the two formats.
eg: $product->at__attributes['part_number']
But that's not really a particularly good solution, IMHO.

Categories