Foreach - determine if key exists in each iteration - php

I have the following Array.
I am trying to figure out how to create an if statement in the foreach that will set true or false based on if any of the individual indexes has [Customer_Facing_Comments__r]
I am using this code - however, this just tells me if [Customer_Facing_Comments__r] is in the array - which it is, every time. I need to see if it is in each index [0], [1]..etc...and set true or false base on that.
CODE:
foreach($queryResult->records as $record){
if (array_key_exists("Customer_Facing_Comments__r",$record)) {
$test = 'true'; }
else { $test = 'false'; } }
QueryResult Object
(
[queryLocator] =>
[done] => 1
[records] => Array
(
[0] => stdClass Object
(
[Id] => 5003xx0255mhcAAA
[Account] => stdClass Object
(
[Id] => 0010cxx026IwsTAAS
[Name] => xxx
)
[AccountId] => 0010c0xxwsTAAS
[Customer_Facing_Comments__r] => stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[Id] =>
[Comment__c] => test string
[CreatedDate] => 2021-02-13T00:25:50.000Z
[Trouble_Ticket__c] => 5003x0000255mhcAAA
)
)
[size] => 1
)
[Type] => Service Down
)
[1] => stdClass Object
(
[Id] => 5003x000024Y6TpAAK
[Account] => stdClass Object
(
[Id] => 0010c0cccc6IwsTAAS
[Name] => test
)
[AccountId] => 0010c00cccIwsTAAS
)

Just expose the key in the foreach and use that in your result array $test:
foreach($queryResult->records as $key => $record){
if (isset($record->Customer_Facing_Comments__r)) {
$test[$key] = 'true';
} else {
$test[$key] = 'false';
}
}

Related

unset std object whole key based condition check

trying to filter data from std object to get result only with status = Active
here is my data =
$newresults =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30509
[status] => InActive
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
in foreach loop i need to get new array of std object with status = active only
so far i am trying to do this with
foreach ($newresults as $key => $value) {
if($value->status == 'Inactive')
unset($newresults[$key]);
}
$newresults[]=$value;
}
return $newresults;
thanks in advance i am sure i can do it this way but i might be doing mistake somewhere
expected output =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
You could just use array_filter:
$newresults = array_filter($newresults, function ($v) { return $v->status == 'Active'; });
print_r($newresults);
Output:
Array
(
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
)
Demo on 3v4l.org
If you want the array to be re-indexed starting at 0, just use array_values on the result.
That should work where you just remove those "Inactive" ones.
foreach ($newresults as $key => $value) {
if ($value->status == 'Inactive') {
unset($newresults[$key]);
}
}

json array sort by value in php

I have JSON arrays of objects. I am trying to sort an array using usort. I want to use value field from field_listing_order. It sorted using value. I am missing something but not able to figure it out. please review the code. Thanks!
stdClass Object
(
[node_title] => abc
[nid] => 2281
[field_api_order_value] => 201
[field_node_entity_type] => node
[_data] => Array
(
[nid] => Array
(
[entity_type] => node
[entity] => stdClass Object
(
[title] => abc
[field_listing_order] => Array
(
[und] => Array
(
[0] => Array
(
[value] => 8
[format] =>
[safe_value] => 8
)
)
)
)
)
)
)
stdClass Object
(
[node_title] => abc
[nid] => 2243
[field_api_order_value] => 204
[field_node_entity_type] => node
[_data] => Array
(
[nid] => Array
(
[entity_type] => node
[entity] => stdClass Object
(
[title] => abc
[field_listing_order] => Array
(
[und] => Array
(
[0] => Array
(
[value] => 3
[format] =>
[safe_value] => 3
)
)
)
)
)
)
) stdClass Object
(
[node_title] => abc
[nid] => 2431
[field_api_order_value] => 242
[field_node_entity_type] => node
[_data] => Array
(
[nid] => Array
(
[entity_type] => node
[entity] => stdClass Object
(
[title] => abc
[field_listing_order] => Array
(
[und] => Array
(
[0] => Array
(
[value] => 1
[format] =>
[safe_value] => 1
)
)
)
)
)
)
)
and So on ...
foreach ($view->result as $result) {
$node = $result->_data['nid']['entity'];
$listing_order = $node->field_listing_order[LANGUAGE_NONE][0];
.....
// code goes here and it works well. sorting issue
}
usort ($node->field_listing_order[LANGUAGE_NONE][0], function($a, $b){
return strcmp($a->value, $b->value);
}); ?>
If you need to sort all the nodes using the field_listing_order value, you need to compare the values along the full path, from the first object to the value:
usort($view->result, function($a, $b) {
$la = $a->_data['nid']['entity']->field_listing_order[LANGUAGE_NONE][0]['value'];
$lb = $b->_data['nid']['entity']->field_listing_order[LANGUAGE_NONE][0]['value'];
return $la - $lb ;
});
In this case $a and $b are two different nodes which could be compared. That why you should compare the field_listing_order's value of these nodes. The answer is working with $la- $lb

Add Array to Existing Object

This seems pretty easy, but I can't figure it out. I have an existing array of objects that was json_decoded. I need to iterate over those objects, append a new array to each, and then put the overall array back together. I can't get the new array to append in the correct place.
function appendToArray($arrayOfObjects) {
$newArray = array();
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$rebuiltObject = array();
array_push($rebuiltObject, $object);
$rebuiltObject['new_stuff'] = $newObject;
// $rebuiltObject[0]['new_stuff'] = $newObject;
array_push($newArray, $newObject);
}
return $newArray;
}
Here is an example of one of the objects that I start with (after json_decode of course:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
)
When this is done, what I want is this:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
But what I get is this:
[0] => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
),
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
Notice how [new_stuff] is outside of the original object. I need to get it inside. Everything else I've tried crashes and I'm totally out of ideas. Can anyone see how I can do this? Thank you!
You solution is one string:
$object->new_stuff = $newObject;
because every $object is object and not array. And adding new property to object is done via -> and not with [].
Full code:
function appendToArray($arrayOfObjects) {
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$object->new_stuff = $newObject;
}
return $arrayOfObjects;
}
You can just array_walk and change the object inplace:
array_walk($arrayOfObjects, function(&$item) {
$item->new_stuff = ["newItems" => ['item1', 'item2', 'item3'], etc];
});

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

Undefined offset: 1 in AND Trying to get property of non-object in

I am success to import email contact with yahoo Oauth API. And I can see that all my contact email is listed in the page when I echo it. However, while it success to print the email, there is an error message there :
Trying to get property of non-object in globalses.php on line 295 AND
Undefined offset: 1 in globalses.php on line 295
This is the code who shows that error:
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($body) {
//logit("callcontact:INFO:response:");
//print(json_pretty_print($body));
$yahoo_array = json_decode($body);
echo "<pre/>";
//print_r($yahoo_array);
foreach($yahoo_array as $key=>$values){
foreach($values->contact as $keys=>$values_sub){
// echo '<pre/>';
// print_r($values_sub);
// echo $values_sub->fields[1]->value->givenName;
$email = $values_sub->fields[1]->value; //This is line 295
if(trim($email)!="")
$newList .= $email.",";
}
}
}
$retarr = $newList."";
}
return $retarr;
[UPDATE] Th print result of $values->contact
Array
(
[0] => stdClass Object
(
[isConnection] =>
[id] => 50331977
[fields] => Array
(
[0] => stdClass Object
(
[id] => 50332026
[type] => email
[value] => academic_interlingua#cbn.net.id
[editedBy] => OWNER
[flags] => Array
(
)
[categories] => Array
(
)
)
)
[categories] => Array
(
)
[error] => 0
[restoredId] => 0
)
[1] => stdClass Object
(
[isConnection] =>
[id] => 41
[fields] => Array
(
[0] => stdClass Object
(
[id] => 63
[type] => email
[value] => access#sampoernafoundation.org
[editedBy] => OWNER
[flags] => Array
(
)
[categories] => Array
(
)
)
)
[categories] => Array
(
)
[error] => 0
[restoredId] => 0
)
[2] => stdClass Object
(
[isConnection] =>
[id] => 50331986
[fields] => Array
(
[0] => stdClass Object
(
[id] => 50332036
[type] => email
[value] => activeindonesia#yahoo.com
[editedBy] => OWNER
[flags] => Array
(
)
[categories] => Array
(
)
)
[1] => stdClass Object
(
[id] => 50332037
[type] => guid
[value] => APQMLKWC3QLQRAMYZQABSF63ZA
[editedBy] => OWNER
[flags] => Array
(
[0] => Y360
)
[isConnection] =>
[categories] => Array
(
)
)
)
[categories] => Array
(
)
[error] => 0
[restoredId] => 0
)
[UPDATE]
foreach($values->contact as $keys=>$values_sub){
if(property_exists($values_sub, 'value') && !is_array($values_sub->value))
//echo $values_sub->fields[1]->value->givenName;
$email = $values_sub->fields[1]->value;
if(trim($email)!="")
$newList .= $email.",";
[UPDATE] the result of var_dump
academic_interlingua#cbn.net.idstring(31) "academic_interlingua#cbn.net.id"
access#sampoernafoundation.orgstring(30) "access#sampoernafoundation.org"
APQMLKWC3QLQRAMYZQABSF63ZAstring(26) "APQMLKWC3QLQRAMYZQABSF63ZA"
activeindonesia#yahoo.comstring(25) "activeindonesia#yahoo.com"
ade.nugraha#bisnis.co.idstring(24) "ade.nugraha#bisnis.co.id"
IKN34TUEMHOJNOBUJQP5D2CBDQstring(26) "IKN34TUEMHOJNOBUJQP5D2CBDQ"
adebete#yahoo.comstring(17) "adebete#yahoo.com"
aditamiva.recruitment#gmail.comstring(31) "aditamiva.recruitment#gmail.com"
admin#goodlife.co.idstring(20) "admin#goodlife.co.id"
admin#klaudia.p.htstring(18) "admin#klaudia.p.ht"
admin#l-cq.comstring(14) "admin#l-cq.com"
admin#mujahidpress.comstring(22) "admin#mujahidpress.com"
agoes#kesaintblanc.co.idstring(24) "agoes#kesaintblanc.co.id"
agro.rekrutmen#agromediagroup.comstring(33) "agro.rekrutmen#agromediagroup.com"
You are accessing the email by its fields as:
$email = $values_sub->fields[1]->value; //This is line 295
When you see the first element of an array, there is no any fields with key 1, since it is only value in the array. $fields[0].
By seeing your code and the actual array, i come up with the following, this may not be the complete solution, but hope guides towards the result.
So this must be something like this:
foreach($values->contact as $keys=>$values_sub){
$fields = $values_sub->fields;
foreach($fields as $field){
if(property_exists($field,'value') && !is_array($field->value)){
echo (string) $field->value;
}
}
}

Categories