How to properly access to array objects - php

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..

Related

Access Multi dimensional array through a dynamic variable

I am trying to pass a dynamic variable into a multidimensional array.
This is the actual code:
for($i = 0; $i < count($social ["#object"] -> field_sector ["und"]); $i++){
echo $social ["#object"] -> field_sector ["und"] [$i] ["taxonomy_term"] -> name;
}
Since I want to re-use this code for multiple types, I created a function
function render_multi_array ($parent, $field_name) {
for($i = 0; $i < count($parent ["#object"] -> $field_name ["und"]); $i++){
echo $parent ["#object"] -> $field_name ["und"] [$i] ["taxonomy_term"] -> name;
}
}
The issue is happening with $field_name as I am unable to provide this dynamically. Any idea how I can make this function work?
Sample array is follows:
Array
(
[#title] => Sector
[#field_name] => field_sector
[#object] => stdClass Object
(
[vid] => 1079
[uid] => 30
[vuuid] => 83ab0817-0175-4541-b20e-93611c20c026
[nid] => 1077
[type] => random_study
[field_random_id] => Array
(
[und] => Array
(
[0] => Array
(
[value] => CS_525
[format] =>
[safe_value] => CS_525
)
)
)
[field_sector] => Array
(
[und] => Array
(
[0] => Array
(
[tid] => 411
[taxonomy_term] => stdClass Object
(
[tid] => 411
[vid] => 10
[name] => Sample title goes here.
)
)
[1] => Array
(
[tid] => 248
[taxonomy_term] => stdClass Object
(
[tid] => 248
[vid] => 10
[name] => Energy
)
)
)
)
In PHP 7 the code should work as written. PHP 7.0 changed evaluation order to strictly left to right.
In PHP 5, you'll get an illegal string offset warning because PHP is trying to first evaluate $field_name["und"] (e.g. "field_sector"["und"]) and use the result of that as the property name in #object rather than evaluating $parent["#object"]->$field_name to get the array and then accessing that with ["und"].
You can prevent that by bracketing the variable like this:
function render_multi_array ($parent, $field_name) {
for ($i = 0; $i < count($parent["#object"]->{$field_name}["und"]); $i++){
echo $parent ["#object"]->{$field_name}["und"][$i]["taxonomy_term"]->name;
}
}
Adding those brackets won't cause any problems if you upgrade to PHP 7 later.
By the way, it looks like this code would be simpler with a foreach loop instead.
function render_multi_array ($parent, $field_name) {
foreach ($parent['#object']->{$field_name}['und'] as $item) {
echo $item['taxonomy_term']->name;
}
}

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]);
}
}

assigining new key value pair to stdclass object in foreach php

Im fetching a pdo object with data from the database. now when i foreach this data I want to add extra key values but this doest work.
foreach ($deliveryCompanies as $k=>$v) {
$k->test = 'test';
}
this returns
Type: ErrorException
Code: 2
Message: Attempt to assign property of non-object
the object looks like this
Array
(
[0] => stdClass Object
(
[delivery_id] => 2
[delivery_location_id] => 34
[delivery_category_id] => 1
)
[1] => stdClass Object
(
[delivery_id] => 4
[delivery_location_id] => 34
[delivery_category_id] => 1
)
)
1
That's because $k is the key, not the value. You need to do $v->test ='test';

How to target value in this type of array

I have an array stored in variable $user_top_cat. I loop through all the users on my site and this variable stores their top categories.
On a random user, print_r() gives us:
Array (
[0] => stdClass Object ( [category] => 16 [count] => 8 )
[1] => stdClass Object ( [category] => 17 [count] => 2 )
[2] => stdClass Object ( [category] => 24 [count] => 2 )
)
Now, I want to store the category 17's count value in variable $category_17_count as a string. How do I do this?
Note that the $user_top_cat differs depending on which user I target...
I don't know why you'd want to but yes you could use the category to concatenate it and turn it into a variable then assign the value:
foreach($user_top_cat as $values) {
$cat_num = $values->category;
${"category_".$cat_num."_count"} = $values->count;
}
Sample Output
Will you could use variable varaibles, but how would you know which variables exist?
foreach ($user_top_cat as $cat){
${'category_'.$cat->category.'_count'} = $cat->count;
}
You'd probably be better using an array
foreach ($user_top_cat as $cat){
$categories[$cat->catergory]=$cat->count;
}
Something like:
foreach( $user_top_cat as $myObj ) {
if( $myObj['category'] == 17 ) {
$category_17_count = (string)$myObj['count'];
}
}

php stdClass check for property exist

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";
}
}
}

Categories