Get an array from an object | php - php

How can I get the array from a object? I'm trying to get to the empty array so that I can validate on it's empty state.
$object = Illuminate\Database\Eloquent\Collection Object;
print_r($object);
if(empty($object->array)){
}
output
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
)
)

The object is of the type Eloquent\Collection which means that it has access to a set of methods.
Eloquent\Collection | available methods
Collection provides a set of methods to validate the state of an array inside the Object. Two of which are interesting in the case described by me (OP):
IsEmpty
IsNotEmpty
Implementation
$website = $this->websitedb->findOneByUrl($this->url);
if($website->isNotEmpty()){
$uniqueId = rand() . $website[0]->id;
//save scan to database
$this->scan = $this->scandb->create($website[0]->id, $uniqueId);
$this->scandb->createModule($this->scan->id, $options);
}

Try like this:
if ($object->array === array()) {
echo 'this is explicitly an empty array!';
}

Related

PHP arrays work differently for objects vs values [duplicate]

This question already has answers here:
How do I create a copy of an object in PHP?
(9 answers)
Closed 3 years ago.
Here's my code:
$words = array();
$word = "this";
$words[] = $word;
$word = "that";
$words[] = $word;
print_r($words);
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word;
$word->setWord("that");
$class_words[] = $word;
print_r($class_words);
exit;
Here's the output:
Array
(
[0] => this
[1] => that
)
Array
(
[0] => word Object
(
[text:word:private] => that
)
[1] => word Object
(
[text:word:private] => that
)
)
I expected the second output to match the first in that the array should store 'this' and 'that'. It seems array_name[] = <item> makes a copy to the item when it's an array of values but not so when it's an array of objects. How do I make it copy the object to the array instead copying a reference to the object? Do I need to create a new object each time I need to add an object to the array?
If you want to copy the value of the object into the array you need to write a "getter" for the value e.g.
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
public function getWord() {
return $this->text;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word->getWord();
$word->setWord("that");
$class_words[] = $word->getWord();
print_r($class_words);
Output:
Array
(
[0] => this
[1] => that
)
Demo on 3v4l.org
$x = new X(); stores a reference to an object into $x. A subsequent $y = $x; copies the reference, not the object, so $x and $y both refer to the same object.
PHP has rather complex semantics regarding references.
Objects are always references; all your uses of $word refer to the same object and the same data structure. You need to do:
$class_words=[new word('this'),new word('that')];
Both elements of your array hold the same object. So whenever you make a change in that object, all references to that object will show that change-- they're all referring to the same object in its current state.
As mentioned previously, if you want different values, you need to either instantiate new objects, or get the property value via a getter() that returns a simple value (string, integer, boolean, etc), not the object itself.
As a side note, you can leverage the referential nature of objects to chain methods ($Obj->method1()->method2()->method3()) by having a method return a reference to the object, i.e., return $this;

Why stdClass is coming instead of our custom object name?

Here My class name is User, When I print my class properties I'm getting my objective name properly. After that, I encoded the data with json_encode(). and then I decoding with json_decode(). I'm getting stdClass objective why?
<?php
class User
{
public $name;
public $age;
public $salary;
}
$user = new User();
$user->name = 'Siddhu';
$user->age = 24;
$user->salary = 7000.80;
print_r($user);
//Output: User Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
print_r(json_encode($user));
//Output: {"name":"Siddhu","age":24,"salary":7000.8}
$d = json_encode($user);
$s = json_decode($d);
print_r($s);
//Output: stdClass Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
If you noticed stdClass is coming, How can I change to user
There is no direct way you can get data in class object either you need to used custom method to decode else you can use serialize() && unserialize() function to get data in the class object when you decode;
$serialized_user_object = serialize($user);
$deserialized_user_object = unserialize($serialized_user_object);
In json_decode you can pass true in second argument if you want data as array.
like this.
var_dump(json_decode($json, true));
to know more about json_decode see here.
The reason this happens can be demonstrated quite easily...
class foo{
public $bar = 'bar';
}
$json = json_encode(new foo);
echo $json."\n\n";
print_r(json_decode($json));
Output
{"bar":"bar"}
stdClass Object
(
[bar] => bar
)
Sandbox
As you can see the output {"bar":"bar"} contains no information about what if any class this was, it could have been ['bar'=>'bar'] and the JSON would be the same... Then when decoding it, you don't have json_decode set to return as an array (second argument set to true), which is fine as that's not really what you want, but when it's set that way you get stdClass objects instead of an associative array for items with non-numeric keys. In short there is no way to recover the class "foo" from the json {"bar":"bar"} as that information does't exist (you can make it exist, but that's another tale for another day).
Using serialize we get something very different.
class foo{
public $bar = 'bar';
}
$json = serialize(new foo);
echo $json."\n\n";
print_r(unserialize($json));
Output
O:3:"foo":1:{s:3:"bar";s:3:"bar";}
foo Object
(
[bar] => bar
)
Sandbox
This O:3:foo means an Object with a class name 3 in length named "foo". So it preserves that information for PHP to use when "decoding" the data.
The whole thing reads like this:
Object (3) "foo" with 1 property named (s)tring (3) "bar" with a value of (s)tring (3) "bar", or something like that.
Make sense.
AS a note PHP's serialize is less portable then JSON, as it only works in PHP, It's also much harder to manually edit then JSON, but if you really want to encode a class than that is the easiest way to do it. That said you can also "repopulate" the class from JSON data, but that can also be hard to maintain.

PHP - adding an object with its properties to array

I have a problem with modifying an array.
foreach ($page->getResults() as $lineItem) {
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
This code gives a result:
Array
(
[0] => Google\AdsApi\Dfp\v201611\Location Object
(
[id:protected] => 2250
[type:protected] => COUNTRY
[canonicalParentId:protected] =>
[displayName:protected] => France
)
)
I'm trying to add another, [1] , same type of object to this array.
I made a class to create and add an object:
class Location{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');
array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);
Then, if I pass this into print_r() function
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
It shows the same result.
In the end, I need to send this updated whole $lineItem to this function
$lineItems = $lineItemService->updateLineItems(array($lineItem));
But seems like before sending I can't properly add an object to the array.
Thanks in advance.
PHP returns arrays as a value instead of as a reference. This means you must set the modified value back somehow.
Looking at the library apparently in question, there seems to be setExcludedLocations method for that purpose.
So your code should be something like:
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);

How to create array of objects in php

I'm attempting to create an array of objects in php and was curious how I would go about that. Any help would be great, thanks!
Here is the class that will be contained in the array
<?php
class hoteldetails {
private $hotelinfo;
private $price;
public function sethotelinfo($hotelinfo){
$this->hotelinfo=$hotelinfo;
}
public function setprice($price){
$this->price=$price;
}
public function gethotelinfo(){
return $hotelinfo;
}
public function getprice(){
return $price;
}
}
And here is what I am attempting to do-
<?PHP
include 'file.php';
$hotelsdetail=array();
$hotelsdetail[0]=new hoteldetails();
$hotelsdetail[0].sethotelinfo($rs);
$hotelsdetail[0].setprice('150');
?>
The class attempting to create the array doesn't compile but is just a best guess as to how I can do this. Thanks again
What you should probably do is:
$hotelsDetail = array();
$details = new HotelDetails();
$details->setHotelInfo($rs);
$details->setPrice('150');
// assign it to the array here; you don't need the [0] index then
$hotelsDetail[] = $details;
In your specific case, the issue is that you should use ->, not .. The period isn't used in PHP to access attributes or methods of a class:
$hotelsdetail[0] = new hoteldetails();
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
Note that I capitalized the class, object, and function names properly. Writing everything in lowercase is not considered good style.
As a side note, why is your price a string? It should be a number, really, if you ever want to do proper calculations with it.
You should append to your array, not assign to index zero.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
This will append the object to the end of the array.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
This would create an array with three objects, appending each one successively.
Additionally, to correctly access an objects properties, you should use the -> operator.
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
You can get the array of object by encoding it into json and decoding it with $assoc flag as FALSE in json_decode() function.
See the following example:
$attachment_ids = array();
$attachment_ids[0]['attach_id'] = 'test';
$attachment_ids[1]['attach_id'] = 'test1';
$attachment_ids[2]['attach_id'] = 'test2';
$attachment_ids = json_encode($attachment_ids);
$attachment_ids = json_decode($attachment_ids, FALSE);
print_r($attachment_ids);
It would render an array of objects.
output:
Array
(
[0] => stdClass Object
(
[attach_id] => test
)
[1] => stdClass Object
(
[attach_id] => test1
)
[2] => stdClass Object
(
[attach_id] => test2
)
)

PHP JSON get the name of an object

<?
stdClass Object
(
[image_header] => Array
(
[0] => stdClass Object
(
[img] => /headers/header.jpg
)
)
)
?>
Object name image_header is variable, so it can be any string. Can I access this string without knowing what it is?
#Jon his answer was satisfying for me.
For others who want to use variable objectnames this way:
To acces this object with the variablename I had to use curly brackets:
$key = key(get_object_vars($_json));
$_json->{$key}[0]->img;
You can do it conveniently with get_object_vars:
$propertyName = key(get_object_vars($object));
If you don't know what the name of the property is, you can use PHP's Reflection classes, or more simply use get_object_vars().
get_object_vars() is probably what you're looking for here - it "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." So, you get the property names and their values returned in an associative array.
Alternatively, you could use some of PHP's reflection magic, although it might be a bit overkill here, depending on your end goal. The reflection classes are very powerful, and may be worth using if you have more complex requirements for what you're trying to achieve. As an example:
// let's say $obj is the object you provided in your question
// Instantiate the reflection object
$reflector = new ReflectionClass($obj);
// Get properties of $obj, returned as an array of ReflectionProperty objects
$properties = $reflector->getProperties();
foreach ( $properties as $property ) {
echo $property->getName(); // In your example, this would echo 'image_header'
}
There are a couple of possibilities. If you're using json_decode() you can pass true in as the second parameter to parse the data as an associative array.
$data = json_decode($myJson, true);
print_r( $data['image_header'] );
You can also access an object property from a variable like this.
$myProperty = 'image_header';
print_r( $data->$myProperty );
If by "you don't know what it is" you mean you don't know the key at all you can use my first example and use array_values() to get the values by index.
$values = array_values($data);
// image_header
print_r( $values[0] );

Categories