Convert an array into an object in PHP - php

I have an array that I access like this:
$item['id'];
What can I do to the array to access it like this instead?
$item->id

Use this code:
$item = (object) $item;
echo $item->property;
The -> syntax is for objects, not associative arrays. You can use the (object) cast operator to cast an array into an object of the class stdClass though.

Cast it to (a stdClass) object:
$item = (object) $item;

If that array is coming from a database, such as mysql you can fetch objects instead of arrays with mysql_fetch_object() or set the flag PDO::FETCH_OBJ if you are using PDO.
Maybe it is not relevant to you however ...

You need to convert it into an object
$item = (object) $item;
echo $item->id;

Related

get object values as array in php

I have object with setter and getter
class obj{
private $a;
private $b;
}
I would like to create an array that get only the value of the object , for example
array = ["1","2"]
tried get_object_vars but its an associative array
To condense an associative array to an indexed array, use array_values:
array_values(get_object_vars($object));
However, given that you have private member variables, you might just want to use an array cast instead of get_object_vars:
array_values((array)$object);
See it online at 3v4l.org.

Know if an object has sub properties in PHP

How do I know if an arbitrary object has any properties in PHP?
I need it for a recursive search on JSON objects as a break condition
i.e break search when the object has no more sub-objects.
I thought of property_exists but it checks a particular property, while I want to know if any property exists.
You can use a foreach loop:
foreach (new object as $prop => $value) {
echo "property \$$prop is $value\n";
}
Also You can do it conveniently with get_object_vars:
$propertyName = key(get_object_vars($object));
The function get_object_vars() will return a list of all accessible properties on an object.
You can try to use this function:
http://php.net/manual/en/function.get-object-vars.php
From the docs:
Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.
You can also use the ReflectionClass to get the object properties like this:
$obj = new YourObjectClass;
$reflect = new ReflectionClass($obj);
$props = $reflect->getProperties();
foreach ($props as $prop) {
print $prop->getName() . "\n";
Casting the object to an array and performing a count on the resulting array will tell you if an object has properties.
$foo = new Bah();
$propertiesAsArray = (array) $foo;
if(count($propertiesAsArray)) {
//this object has properties
} else {
//this object does not have properties
}
You could use :
if(isset($yourobject)){
//YourCode
}
in a loop to see if the object have anything already set.

Object of class Database_MySQL_Result could not be converted to string

views.php
$events = array($events); //convert $events objects to array
asort($events); //sort array in ascending order
foreach($events as $event): //iterate array
echo $event; //getting error here
endforeach;
tried this also,
foreach($events as $key => $event): //iterate array
echo "$key = $event\n"; //getting error here
endforeach;
I am trying to iterate the array in foreach loop but i am getting this error "ErrorException [ Recoverable Error ]: Object of class Database_MySQL_Result could not be converted to string"
Need help to solve this.
$events = array($events);
This line does not convert objects to array, but it just inserts object into array;
So $events[0] equals old $events;
I don't know how you pull your data from DB, but as long as it's Kohana, maybe this would work:
$events = $events->as_array();
try casting events as an array, instead of inserting it into array like:
$events = (array)$events;
this will result in all public properties on the $events object being set as an assoc array.

Populating an object's properties

Consider following code:
$ob=new MyObject();
$ob->name=$_GET['name'];
$ob->email=$_GET['email'];
...
$ob->foo=$_GET['foo'];
Is there any cleaner way (language mechanism) to populating an object's property with an associative array. (without using foreach or similar constructs)?
As this answer states, you can do:
$ob = (Object) $a;
Only foreach? You can other loop: while, for. What about goto?
Also you can use some functions without obvious loop.
$object = new MyObject();
$array = array('foo' => 1, 'baz' => 2);
array_walk($array, function ($value, $field)use($object){
$object->$field = $value;
});

Can't access array by index, but can iterate with foreach

How come that I can't access array by index $obj->property[0] but can iterate through the array (each has only one value) and then get the value.
foreach($obj->property as $inner_obj)
{
foreach($inner_obj->property as $inner_inner_obj)
echo $inner_inner_obj->property;
}
If I access array by index I get Undefined offset: 0
Edit: Output of var_dump
array(1) {
[0]=> object(FooClass)#141 {
// yadda yadda
}
}
if you make class by implements Countable, Iterator you can make a object that work with foreach but it is not array
$obj is not array its stdClass Object and
because of that $obj->property[0] will show you Undefined offset: 0
try to use it like this for getting 1st value of property
$obj->property->property;
Because you're looping over properties of an array in a foreach. With [0] you explicitly try to access it as an array. You can have your object extend ArrayObject and make php access your object as an array which is what you want I think.
The interfaces that gives the ability to use your object as an array:
http://www.php.net/manual/en/class.arrayaccess.php
http://www.php.net/manual/en/class.countable.php
http://www.php.net/manual/en/class.iteratoraggregate.php
The object itself which you can extend:
http://www.php.net/manual/en/class.arrayobject.php
Imo, it's never a good idea to loop over an object without array interface as it means you are using public variables. My suggestion is to always make them protected or private unless not possible otherwise (SOAP?). You can access them by getters and setters.
The $obj->property could be an array without having key 0.
The keys in your array might not be numeric. So your array might be an associative array not a regular.
If you want numeric indexing try this:
$numArray = array_values($obj->property);
var_dump($numArray);
If you want to access the first value of an array use:
$first = reset($obj->property);
It works if your variable is an array.

Categories