PHP object property notation - php

I suddenly stuck here:
$source = (object) array(
'field_phone' => array(
'und' => array(
'0' => array(
'value' => '000-555-55-55',
),
),
),
);
dsm($source);
$source_field = "field_phone['und'][0]['value']";
dsm($source->{$source_field}); //This notation doesn't work
dsm($source->field_phone['und'][0]['value']); //This does
dsm() is Drupal developer function for debug printing variables, objects and arrays.
Why $source object doesn't understand $obj->{$variable} notation?
Notice: Undefined property: stdClass::$field_phone['und']['0']['value']

Because your object does not have a property that is named "field_phone['und'][0]['value']". It has a property that is named "field_phone" which is an array which has an index named "und" which is an array which has an index 0 and so on. But the notation $obj->{$var} does not parse and recursively resolve the name, as it shouldn't. It just looks for the property of the given name on the given object, nothing more. It's not like copy and pasting source code in place of $var there.

Related

YouTube Feed has an object called #attributes how can I access it?

I am trying to get a YouTube RSS feed to work but I am struggling to get one of the attributes I need out of it. I have never seen part of the array starting with an # sign so I think it may be some sort of a special element but I'm not sure. Code below and what I have already tried after.
Feed:
<?php
$xml->entry =
SimpleXMLElement::__set_state(array(
'id' => 'yt:video:DjwM9SHJznM',
'title' => 'JD19AT - Joomla! in der Uni - Community-Arbeit als Lehrveranstaltung',
'link' =>
SimpleXMLElement::__set_state(array(
'#attributes' =>
array (
'rel' => 'alternate',
'href' => 'https://www.youtube.com/watch?v=DjwM9SHJznM',
),
)),
'author' =>
SimpleXMLElement::__set_state(array(
'name' => 'J and Beyond e.V.',
'uri' => 'https://www.youtube.com/channel/UCy6ThiEDnalZOd_pgtpBk1Q',
)),
'published' => '2019-03-30T16:49:53+00:00',
'updated' => '2019-05-09T16:56:18+00:00',
));
?>
Code:
$feed = $youtubeChannelFeed;
$xml = simplexml_load_file($feed);
$html = "";
This works $xml->entry->title;
but this doesn't $xml->entry->link it just says "SimpleXML Object"
As it says object I then tried using both -> arrow and ['attribute'] notation.
I tried escaping the # with a \# but that just caused an error.
How can I traverse the tree and get the value of to #attributes->href ?
The way I always try to remember this is that you can use an arrow or brackets to access data in an array or object.
Array begins with A, but it chooses the one that's does not begin with A. Object is the one left over. That's how I remember it at least.
In this case, although it was calling it a SimpleXMLObject it was actually showing me that it's an array in the print_r. So I had to use brackets to access like so:
$xml->entry->link[0]['href']
I couldn't work out how to access #attributes but I remember now that you don't need to know the name to access it, you can do it using number format too.
If I'm honest I don't really know how I could access the first part with arrows as that appears to be an array too.

accessing multidimensional array in laravel blade

I'm trying to access the 'cat' value in my array below, coming from my controller.
If I dump $tempCategories it shows the array correctly but my html is showing nothing for some reason.
Am I not accessing the element correctly?
I expect to see
Wood
Metal
controller.php
$tempCategories = array(
0 => array(
'cat' => 'Wood'
),
1 => array(
'cat' => 'Metal'
),
);
blade.php
#foreach($tempCategories as $cat)
<h5>{{$cat->cat}}</h5>
#endforeach
You are trying to access an array as object
Replace
<h5>{{$cat->cat}}</h5>
With
<h5>{{$cat['cat']}}</h5>
If you want to access it with arrow operator - convert your array to object or collection first (in your controller)
$object = (object) $array;
Or
$collection = collect($array);

How to cast multiple array elements to object

I'm trying to create an array containing multiple objects.
I wrote this code (it's a member of an existing class)
public static $Roles = [
(object) ['code' => 'SO', 'name' => 'Socio'],
(object) ['code' => 'RESP', 'name' => 'Responsabile zona'],
(object) ['code' => 'AMM', 'name' => 'Amministratore'],
];
but I get this error:
syntax error, unexpected '(object)' (object) (T_OBJECT_CAST),
expecting ')'
on the second line.
I thought this should work, because I already used the same cast syntax to define associative array elements:
return view('edit-headquarter', [
'hq' => (object)['name' => '', 'id' => 0],
'submitAction' => 'insert'
]);
I'm doing something wrong?
EDIT: I'm using PHP 5.4.45
I'm not sure, but this can be related as suggested by Martin Persson
If you're using PHP version below v5.6, then you will not be allowed to have an expression as a default value for class members. Other than that, I don't see anything wrong with the way you have declared it.
To cast an associative array to object you can use a bit dirty, but widely used
$obj = json_decode(json_encode($arr));

Accessing data from CakePHP's find() return array

Here's an example of an array that is returned by CakePHP's find() method:
Array
(
[Tutor] => Array
(
[id] => 2
[PersonaId] => 1
)
)
The official documentation shows how to fetch records, but does not show how to iterate through them or even read out a single value. I'm kind of lost at this point. I'm trying to fetch the [id] value within the array. Here's what I've tried:
// $tutor is the array.
print_r($tutor[0]->id);
Notice (8): Undefined offset: 0
[APP\Controller\PersonasController.php, line 43]
Notice (8): Trying to
get property of non-object [APP\Controller\PersonasController.php,
line 43]
I've also tried:
// $tutor is the array.
print_r($tutor->id);
Notice (8): Trying to get property of non-object [APP\Controller\PersonasController.php, line 44]
The -> way of accessing properties is used in objects. What you have shown us is an array. In that example, accessing the id would require
$tutor['Tutor']['id']
Official PHP documentation, "Accessing array elements with square bracket syntax":
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]); //"bar"
var_dump($array[42]); //24
var_dump($array["multi"]["dimensional"]["array"]); //"foo"
?>
The returned value is an array, not an object. This should work:
echo $tutor['Tutor']['id'];
Or:
foreach($tutor as $tut){
echo $tut['Tutor']['id'] . '<br />';
}

PHP dump variable as PHP code

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);
var_export()
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.

Categories