Cannot access php stdClass property on std class object - php

I'm passing an ACF std class object of values to a function as a value and when trying to read it in the function, it shows up as an object but when I try to access a property Notice: Trying to get property "type" of non-object
function createACFProductLicenses($acfData, $propertyString){
$newData = array();
if(isset($acfData->{$propertyString})){
$data = (array)$acfData->{$propertyString};
foreach ($data as $key => $value) {
print_r($value);
// prints out
// stdClass Object
// (
// [type] => standard
// [item_id] => 727
// )
print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
}
}
}
// example of how I'm calling it:
// $product['acf'] is an stdClass of acf properties
createACFProductLicenses($product['acf'], 'product_licenses');

The "foreach" set the data structure to $key=>$value or [type] is a $key and "standard" is a $value so you can't print $value->type because the object is actually 'type' => 'standard'.
Also, know that the "foreach" will run your code for each item on the object like for ana array, so you can't just print a specific value when you have different $key.
If you want to display all the items use this:
print_r($key.':'.$value) // this will print: type : standard
Or if you want to only print the [Type] item Try this out:
insted of this
if(isset($acfData->{$propertyString})){
$data = (array)$acfData->{$propertyString};
foreach ($data as $key => $value) {
print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
}
}
}
Try this
if(isset($acfData->{$propertyString})){
$data = (array)$acfData->{$propertyString};
print_r($data['type']);
}
}
I hope this will help, let me know if it didn't work.

Related

CodeIgniter : for each loop Attempt to assign property 'details' of non-object

i am fetching data from two tables as below :
$form['form']=json_decode($this->db->get_where('forms',array(
'id' => $id
))->result()[0]->form_sections);
This gives me following result on printing :
Array
(
[form] => Array
(
[0] => Personal_Information
[1] => Education_
[2] => Professional_Life
)
)
Now i have details against each of these array indexes that i am trying to assign them as below
foreach ($form['form'] as $value){
$value->details=$this->db->get_where('formdata',array(
'form_section' => $value
))->result();
}
Which gives me following error
Message: Attempt to assign property 'details' of non-object
can someone please help me to sort out the issue , i have to assign the index and loop in it in my view
This should help understand and clear up the message:
// Custom data
$Person_Info = 404; // Could be any non-object
$array = array("form" => array( 0 => $Person_Info) );
foreach( $array['form'] as $value ){
$results = new stdClass();
$results->name = "User A";
$value->details = $results; // $results are you fetch request
}
// Output: Attempt to assign property 'details' of non-object in php<8.0
// Output: Uncaught Error: Attempt to assign property "details" on int php>=8.0
Try to print_r or var_dump your $value and see what you are getting. It's not an object for some of your array item.
Edit: If ever in doubt about the data. Use if (is_obejct($var)) php.net/is_object or similar checks based on what you need.

Get a value from within an array of object in Laravel [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 1 year ago.
I am quite new no laravel. I know that it is a pretty basic question. But, I still can't figure it out. Heres my Array output and I want to get the value of name from within this array. This is the output I get in postman after I used print_r:
Array
(
[0] => Array
(
[name] => Test 2322
[id] => 4
)
)
if you want all of them
foreach ($datas as $datavals) {
echo $datavals['name'];
}
If you want 0 array name element value Just call following :
echo $memus[0]['name'];
In case this is a collection you can use the pluck method
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
If in your case you do not have a collection you can create it with the collect method.
In your case:
$myarray = collect($initialArray); //You can ignore this if it is already an array
$nameArray = $myarray->pluck('name')->all();
foreach($nameArray as $name)
{
echo $name; //Test 2322
}
You can iterate the array with foreach on blade and get index="name" for each entry like this:
In View
#foreach($data as $d)
{{$d['name']}}
#endforeach
In Controller
foreach($data as $d){
// This is the value you want
$name = $d['name']
}
Simply write the array name with the indices and key which have to access.Suppose $a[] is array then $a[0]['name'] and the value at zero index of array will be retrieved or you can parse it in loop which will give the value of key ['name'] at every indices.
foreach($a as $item)
{
print_r($item['name']);
}
In newest version of laravel you can use the Arr::pluck() helper function to take an array of all names values.
In your case
Arr::pluck($array, 'name')
Will output
['Test 2322']

PHP ArrayUndefinedOffset But Why?

I have dataset like the following, one of my table column let say prices column store prices in json format, example given below.
<?php
$dataSet[] = array(
"product_id" => 1,
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesStdClassObject = json_decode($dataRow['prices']);
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
print_r($pricesArray);
}
?>
The output of print_r($pricesArray) is the following
Array ( [1] => 29990 [2] => 10000 )
Then why print_r($pricesArray[1]) give me error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
But why?
And finally i found the solution:
According to the documentation here and from the forum here I found a ‘assoc’ parameter of json_decoded method that used with this method and by default its value is FLASE, json_decoded return stdClass objects if you want the returned objects converted into associative arrays then you have to make the ‘assoc’ parameter value to TRUE like the following.
$pricesStdClassObject = json_decode($dataRow['prices'], TRUE);
So the above example code will become like this
<?php
$dataSet[] = array(
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesArray = json_decode($dataRow['prices'], TRUE);
// returned objects will be converted into associative arrays.
print_r($pricesArray);
}
?>
And then you can access the indexed value with no error message :)
print_r($pricesArray[1]); output: 29990
Array type casting with json decoded StdClass Objects is not working properly, you can skip the following piece of code if you are using the ‘assoc’ parameter.
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;

PHP echo value of a object from array

I have a array which I am printing using print_r.
<?php
print_r ($this)
?>
I get following result in my browser.
PackingListForm Object
(
[objShipment:protected] => Shipment Object
(
[objCustomFieldArray] =>
[intShipmentId:protected] => 38
[strShipmentNumber:protected] => 1035
[intTransactionId:protected] => 97
[intFromCompanyId:protected] => 1
[intFromContactId:protected] => 1
[intFromAddressId:protected] => 1
[intToCompanyId:protected] => 2
[intToContactId:protected] => 3
[intToAddressId:protected] => 2
[intCourierId:protected] => 1
[strTrackingNumber:protected] =>
[dttShipDate:protected] => QDateTime Object
)
)
Now I want to print / echo intTransactionId.
I have used following variable to echo the result, but I am getting undefined variable.
<?php
$noted = $this->objShipment->intTransactionId;
print_r ($noted);
?>
I am getting following php exception error in my browser.
Undefined GET property or variable in 'Shipment' class: intTransactionId
Line 33: $noted = $this->objShipment->intTransactionId;
My question is how can I echo / print value of intTransactionId?
intTransactionId is a protected property which means that you can't access it outside of the class itself (or parennt class or child class).
The exception, I think, is thrown in a __get magic method defined in Shipment (or one of its parent classes). This method is called when trying to access an unset property (or non-accesible property).
Please check this behaviour.
First try to convert it into array and then it will be much easier :),
$newArray = (array)$this;
print_r($newArray);//to see what can you get from there
// get_object_vars
$newArray = get_object_vars($object);
The object is from class PackingListForm, have look on that class if you have access and see if there is any get() function.

CodeIgniter: view is not generated in a certain case

Starting from a variable called $data, which is an associative array which includes an object, and whose printed value is this:
Array
(
[item] => stdClass Object
(
[id] => 1
[tipo] => 0
[idioma] => es
[nombre] => Artí­culo de prueba
[titulo] => Esto es un artí­culo de prueba
[alias] => articulo-de-prueba
[texto] => Lorem ipsum etc etc
[url] =>
[video] =>
[fecha_c] => 2012-11-27 10:50:37
[fecha_m] => 2012-11-27 17:00:00
[fecha_p] => 2012-11-28 00:00:00
[destacado] => 0
[status] => 1
)
[imagenes] => Array
(
)
)
I need to filter its value and assign it to another array, this way:
protected function load_form($data = '') {
$this->load->helper('form');
// If item data have been sent, pass it to the form view to edit it.
// Else display empty form for new item.
if (! empty($data)) {
// Data can be an associative array with an object and another array or just an object
if (array_key_exists('item', $data)) {
$this->_vars['item'] =& $data['item'];
}
else {
$this->_vars['item'] =& $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
$view = $this->load->view(ADMIN_FORMS_PATH . $this->_controller . '_form', $this->_vars, true);
/*DEBUG*/ echo $view; // just for debugging purposes
}
The first assignment generates these errors:
A PHP Error was encountered Severity: Notice Message: Undefined index:
item Filename: core/Admin_Controller.php Line Number: 205
A PHP Error was encountered Severity: Notice Message: Object of class
stdClass could not be converted to int Filename:
core/Admin_Controller.php Line Number: 205
It behaves like the item index doesn't exist, and it does. Also, it tries to convert the object to an integer.
Why does it happen and what should I do to fix it?
EDIT:
I was doing &= instead of =&. That's the reason of the errors.
Anyway, the problem persists and the code seems to stop.
EDIT2:
Trying to redefine the problem. It might be something related to CodeIgniter, so I've added the whole function, including CodeIgniter functions.
The load_form() method can be invoked from a request to create a new item, in which case $data is empty, or from a request to edit a given item (in $data). In the first case (creation), the debug line is executed, but not in the second case (edition).
This may be your issue. Near the end you have"$datos['imagenes'];" where it should be "$data['imagenes'];"
if (! empty($data)) {
// Data can be an object, or an array with object + array of images
if (array_key_exists('item', $data)) {
$this->_vars['item'] &= $data['item'];
}
else {
$this->_vars['item'] = $data;
}
if (array_key_exists('imagenes', $data)) {
$this->_vars['imagenes'] = $data['imagenes'];
}
}
Problem solved. It was too simple.
It was inside the view. I was trying to echo:
$item['id']
instead of
$item->id
The item data is being retrieved as an object, not an array. It was causing the problem silently, without any warning, notice or error.
Anyway I appreciate your quick help.

Categories