php stdClass check for property exist - php

I have read some similar issues here but unfortunately find the solution for my case.
Some part of the output for an API connection is as;
stdClass Object (
[page] => 0
[items] => 5
[total] => 5
[saleItems] => stdClass Object (
[saleItem] => Array (
[0] => stdClass Object (
[reviewState] => approved
[trackingDate] => 2013-11-04T09:51:13.420+01:00
[modifiedDate] => 2013-12-03T15:06:39.240+01:00
[clickDate] => 2013-11-04T09:06:19.403+01:00
[adspace] => stdClass Object (
[_] => xxxxx
[id] => 1849681
)
[admedium] => stdClass Object (
[_] => Version 3
[id] => 721152
)
[program] => stdClass Object (
[_] => yyyy
[id] => 10853
)
[clickId] => 1832355435760747520
[clickInId] => 0
[amount] => 48.31
[commission] => 7.25
[currency] => USD
[gpps] => stdClass Object (
[gpp] => Array (
[0] => stdClass Object (
[_] => 7-75
[id] => z0
)
)
)
[trackingCategory] => stdClass Object (
[_] => rers
[id] => 68722
)
[id] => 86erereress-a9e4-4226-8417-a46b4c9fd5df
)
)
)
)
Some strings do not include gpps property.
What I have done is as follows
foreach($sales->saleItems->saleItem as $sale)
{
$status = $sale->reviewState;
if(property_exists($sale, gpps))
{
$subId = $sale->gpps->gpp[0]->_;
}else{
$subId = "0-0";
}
}
What I want is I the gpps property is not included in that string $subId stored as 0-0 in db, otherwise get the data from the string. But it doesn't get the strings without gpps.
Where is my mistake?

Change
if(property_exists($sale, gpps))
with
if(property_exists($sale, "gpps"))
notice how now gpps is passed as string, as per the signature of the property_exists function:
bool property_exists ( mixed $class , string $property )
This function checks if the given property exists in the specified class.
Note:
As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

property_exists is the method designed for this purpose.
bool property_exists ( mixed $class , string $property )
This function checks if the given property exists in the specified class.
Note:
As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Try a simple hack and use count, since the property contains an array, and I guess, that count(array) == 0 is the same case as when the property is not set.
foreach($sales->saleItems->saleItem as $sale)
{
$status = $sale->reviewState;
if(#count($sale->gpps->gpp) && count($sale->gpps->gpp) > 0)
{
$subId = $sale->gpps->gpp[0]->_;
}else{
$subId = "0-0";
}
}
Sure, this is not the most beautiful solution, but since the php-function do not work as expected, I thought a bit more pragmatic.

Another way , get_object_vars
$obj = new stdClass();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;
$ar_properties[]=get_object_vars($obj);
foreach($ar_properties as $ar){
foreach ($ar as $k=>$v){
if($k =="surname"){
echo "Found";
}
}
}

Related

Sorting stdClass Object in two

I want sorting Teams list by "terminland_days" value
I read same question in Stack Overflow https://stackoverflow.com/a/38237197/5006328 but still have problem on this.
This is my PHP (PHP >=7.4) code:
public function display($tpl = null) {
// myval get from other model
//print_r ($myval);
$myval = Array
(
[0] => stdClass Object
(
[id] => 1
[state] => 1
[teams] => {"teams0":{"name":"Jhon","terminland_days":"3"},"teams1":{"name":"Alex","terminland_days":"2"}}
[distance] => 5839.5147520164
)
[1] => stdClass Object
(
[id] => 2
[state] => 1
[teams] => {"teams0":{"name":"Jeff","terminland_days":"12"},"teams1":{"name":"Fred","terminland_days":"1"}}
[distance] => 5839.5147520164
)
);
foreach ($myval as $item) {
$paramsteam = json_decode($item->teams);
foreach ($paramsteam as $team) {
// i want sorting Teams as "terminland_days" value
usort($team, "compare_func");
// error ==> Warning: usort() expects parameter 1 to be array, object given
echo $team->terminland_days;
}
}
}
public function compare_func($a, $b)
{
if ($a->terminland_days == $b->terminland_days) {
return 0;
}
return ($a->terminland_days < $b->terminland_days) ? -1 : 1;
// You can apply your own sorting logic here.
}
as I understand, I must use usort, please help me how I can do it?
When print_r ($team); output:
stdClass Object
(
[name] => Jhon
[terminland_days] => 3
)
stdClass Object
(
[name] => Alex
[terminland_days] => 2
)
stdClass Object
(
[name] => Jeff
[terminland_days] => 12
)
stdClass Object
(
[name] => Fred
[terminland_days] => 1
)
After a few hours of scrutiny, I realized that the best way was to first convert the object to an array and then sort it. so :
$paramsteam = json_decode($item->teams,true);
usort($paramsteam, function ($item1, $item2) {
return $item1['terminland_days'] <=> $item2['terminland_days'];
});
foreach ($paramsteam as $team) {
echo $team['terminland_days'];
}
also #Nico haase thank you

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

Cycling an array and delete item

I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}

issue while converting stdclassobject to array in php

I have an array inside which I have stdclassObjects. I need to convert those stdClassObjects to arrays. Below is the array:
Array
(
[serial] => #253
[details] => stdClass Object
(
[Department] => stdClass Object
(
[value] => CI DATA CENTER
)
[City] => stdClass Object
(
[value] => NYC
)
)
[owner] => Drey
)
Could somebody please assist me?
The super lazy way is json_decode and json_encode:
$multiDimArray = json_decode(json_encode($multiDimObject), true);
The documentation on json_decode specifies the second parameter being:
assoc
When TRUE, returned objects will be converted into associative arrays.
function convertStdClassToArray($stdClass) {
$outputArray = [];
if (is_array($stdClass) || !empty($stdClass)) {
foreach ($stdClass as $field => $value) {
$outputArray[$field] = $this->convertStdClassToArray($value);
}
}
return $outputArray;
}

How to properly access to array objects

I've a result from a webservice's query and I would like to get some values from it. It works but I have PHP notice issues, so I'm probably doing something wrong.
This is the $items variable content :
stdClass Object
(
[response] => stdClass Object
(
[0] => stdClass Object
(
[id] => 275
[corpid] => 16107
[name] => default
[description] =>
[status] => ok
[nbSteps] => 7
)
[defaultItem] => 275
)
[error] =>
[status] => success
)
So I tried something like :
foreach ( $items->response AS $key => $item ) {
if ( $item->name == 'default' ){ // Line 106
$Id = $item->id;
}
}
It works, $Id is equal to 275 but PHP returns a notice :
Notice: Trying to get property of non-object in /home/web/dev/webservice-form.php on line 106
Any help would be greatly appreciated.
EDIT : This is the content of the $item variable (taken from the foreach loop) :
stdClass Object
(
[id] => 275
[corpid] => 16107
[name] => default
[description] =>
[status] => ok
[nbSteps] => 7
)
275
Please note that the '275' is a part of the result.
The problem is the defaultItem entry in your inner object. Your loop will at some point reach this and try to access name, which doesn't exist, because there is no object.
Should be easily solveable with is_object().
You have mixed types, one being an objects, and one an int value, try checking what each item is:
foreach ( $items->response AS $key => $item ) {
if(is_object($item) && $item->name == 'default'){ // Line 106
$Id = $item->id;
}
else {
$Id = $item; // assume it's scalar value
}
}
Obviously it would depend on what else you can expect on what other check you need to add in there..

Categories