Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I append an stdClass Object

Tags:

php

stdclass

I have an stdClass Object like generated by joomla like this

$db->setQuery($sql);
$schoollist = $db->loadObjectList(); 

And the $schoollist variable contains the following stdClass Objects

stdClass Object ( [id] => 1 [col1] => blabla [col2] => 5 [col3] => 208 ) 
stdClass Object ( [id] => 2 [col1] => test1 [col2] => 1 [col3] => 52 ) 

and I need to add another "column" after the query as [col4] => dsdads , so the result will be like this

stdClass Object ( [id] => 1 [col1] => blabla [col2] => 5 [col3] => 208 [col4] => 208) 
stdClass Object ( [id] => 2 [col1] => test1 [col2] => 1 [col3] => 52 [col4] => 208) 

how can I do this?

like image 967
themhz Avatar asked Apr 29 '13 19:04

themhz


People also ask

How to append object in PHP?

The append() function of the ArrayObject class in PHP is used to append a given value onto an ArrayObject. The value being appended can be a single value or an array itself. Parameters: This function accepts a single parameter $value, representing the value to be appended.

What is an stdClass object?

The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.

What does stdClass mean in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How do I print a stdClass?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .


2 Answers

Simply set a new field:

$object->col4 = $value; 

If you need dynamic field names:

$object->$fieldName = $value; 
like image 128
bwoebi Avatar answered Sep 28 '22 02:09

bwoebi


RE dynamic field names.

These should be defined as such.

$object->{$fieldName} = $value; 
like image 37
spoonerise Avatar answered Sep 28 '22 03:09

spoonerise