PHP Soap Request foreach - php

I have a Souap Request and I do not know how I can go through all VoucherCodeItems with foreach.
I tried this, but it dosn't work:
foreach($response->VoucherCodeCollection->VoucherCodeItem AS $key => $val) {
echo "Feld $key hat den Wert: $val<br>";
}
This is what i get when make a print like:
print_r($response);
Result
stdClass Object
(
[TotalResults] => 2
[VoucherCodeCollection] => stdClass Object
(
[VoucherCodeItem] => Array
(
[0] => stdClass Object
(
[Id] => 215523
[ProgramId] => 6767
[Code] =>
[Title] => Adventskalender
[Description] => Im Adventskalender
)
[1] => stdClass Object
(
[Id] => 215453
[ProgramId] => 8476
[Code] =>
[Title] => Wir schenken dir 15 EUR!!
[Description] =>
)
)
)
)

You can't directly echo out the object:
Try:
foreach ($response->VoucherCodeCollection->VoucherCodeItem as $key => $val) {
echo "Feld $key hat den Wert: {$val->Title}<br>";
}

Related

Flatten PHP stdClass object to array maintaining array dimensions

I am working with soap responses that contain nested wrappers and whose child(ren) have nested properties.
I am trying to flatten these response to:
remove the wrappers
flatten the children
maintain the individual children (dimensions)
I am currently working with the following that achieves #1 and #3 however it does not flatten the inner children. Note that $this->response is converted from a stdClass to Array before being flattened.
How can I also flatten down the inner nested child elements?
private function toArray()
{
$this->response = json_decode(json_encode($this->response), true);
return $this;
}
private function flatten($array = null)
{
if (is_null($array)) {
$array = $this->response;
}
if (is_array($array)) {
foreach ($array as $k => $v) {
if (count($v) == 1 && is_array($v)) {
return $this->flatten($v);
}
if (isset($v[0])) {
$this->response = $v;
return $this;
}
unset($this->response);
$this->response[] = $v;
return $this;
}
}
}
...which will transform this:
stdClass Object
(
[ArrayOfDevice] => stdClass Object
(
[Device] => Array
(
[0] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
)
)
...to this:
Array
(
[0] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[name] => Device1
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...and in the case of a single item being returned, this:
stdClass Object
(
[ArrayOfAlarm] => stdClass Object
(
[Alarm] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
)
...to this:
Array
(
[0] => Array
(
[Element] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
You can flatten a single of your items with the following function:
function flatten_item($array)
{
$result = [];
foreach ($array as $k => $v) {
if (is_array($v)) {
$result = array_merge($result, $this->flatten_item($v));
} else {
$result[$k] = $v;
}
}
return $result;
}
When you have an array of results, you can pass this function as the callback to array_map. Only the relevant portion of the code:
if (isset($v[0])) {
$this->response = array_map([$this, 'flatten_item'], $v);
return $this;
}
// Convert single result to an array
$this->response = [$this->flatten_item($v)];
return $this;
Since the response (so far) always has the same structure, you could extract the payload without using recursion, which allows you to also remove the foreach in the flatten function:
function flatten()
{
// Remove outer wrappers [ArrayOfX][X] by extracting the value
$payload = current(current($this->response));
if (isset($payload[0])) {
$this->response = array_map([$this, 'flatten_item'], $payload);
} else {
$this->response = [$this->flatten_item($payload)];
}
return $this;
}
The function found here does just what you want, with a slight modification (commented out concatination of parent keys): https://gist.github.com/kohnmd/11197713#gistcomment-1895523
function flattenWithKeys(array $array, $childPrefix = '.', $root = '', $result = array()) {
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) $result = flattenWithKeys( (array) $v, $childPrefix, $root . $k . $childPrefix, $result);
else $result[ /*$root .*/ $k ] = $v;
}
return $result;
}
Letting $object equal your provided object, use as follows:
$array = json_decode(json_encode($object), true);
$result =[];
foreach( $array['ArrayOfDevice']['Device'] as $key => $value ){
$result[$key] = flattenWithKeys($value);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location2
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
See it run here: http://sandbox.onlinephpfunctions.com/code/851e93389b993a0e44c1e916291dc444f47047d3

stdClass Object foreach PHP loop

Been searching for a solution for my problem. Seams meny has the same q as me, but still haven't got a solution for my problem.
I have a stdClass Object that needs to be printed out in a foreach or somlike like that.
Here is a cut of the result i get with a "print_r($result)".
Array
(
[0] => stdClass Object
(
[id] => 1
[itemDescription] => I
[itemImage] => 2131099833
[itemName] => ABOOD
[itemPrice] => 8
[itemQuantity] => 1
[itemUid] => 1007
[orders] => stdClass Object
(
[date_created] => 0
[id] => 1
[ordered] =>
)
)
[1] => stdClass Object
(
[id] => 2
[itemDescription] =>
[itemImage] => 2131099833
[itemName] => PAPAYA
[itemPrice] => 8
[itemQuantity] => 1
[itemUid] => 1010
[orders] => stdClass Object
(
[date_created] => 0
[id] => 1
[ordered] =>
)
)
)
foreach ($result as $value)
{
foreach ($value as $key=>$value1)
{
if($key=="itemUid")
{
echo $value1;
}
if($key=="itemQuantity")
{
echo $value1;
}
}
}
any easy method
You could do something like this for each stdClass object in your array:
foreach ($stdClassObject as $propName => $propValue) {
echo $propName . '->' . $propvalue;
}
As #arzhed stated in the comments, it's not necessary to use get_object_vars to iterate over the properties of an stdClass object.

how to parse stdclass

I have this data as a response:
stdClass Object
(
[GetReceiveMessagesResult] => stdClass Object
(
[Messages] => Array
(
[0] => stdClass Object
(
[MessageID] => 63012240
[RecipientNumber] => 30006708212212
[SenderNumber] => 09379580052
[Body] => Esm200aliaranbeigi
[ReceiveDate] => 1482389480
)
[1] => stdClass Object
(
[MessageID] => 63012231
[RecipientNumber] => 30006708212212
[SenderNumber] => 09379580052
[Body] => Esp243محسن قائدی
[ReceiveDate] => 1482389454
)
)
)
)
How I can print Messages items ?
$counter=count($results->GetReceiveMessagesResult->Messages);
You can use foreach loop
Try
foreach ($results->GetReceiveMessagesResult->Messages as $msg)
{
echo $msg->MessageID;
}
$counter=count($results->GetReceiveMessagesResult->Messages);
if($counter>0)
{
foreach ($results->GetReceiveMessagesResult->Messages as $msg)
{
echo $msg->MessageID;
echo $msg->RecipientNumber;
}
}

echo json object $stdClass Object array

echo "<pre>"; print_r($data); echo "</pre>";
Gives following output:
$stdClass Object
(
[cartName] => AngularStore
[clearCart] =>
[checkoutParameters] => stdClass Object
(
)
[items] => Array
(
[0] => stdClass Object
(
[sku] => 01
[name] => Product 1
[price] => 600
[quantity] => 1
[stock] => 5
[scheme] => Array
(
[0] => stdClass Object
(
[name] => offerAB
[desc] => Description on the scheme
[no] => 3
[$$hashKey] => 01O
[checked] => 1
)
[1] => stdClass Object
(
[name] => offerXY
[desc] => Description on the scheme
[no] => 5
[$$hashKey] => 01P
)
[2] => stdClass Object
(
[name] => OfferPQ
[desc] => Description on the scheme
[no] => 2
[$$hashKey] => 01Q
[checked] => 1
)
[3] => stdClass Object
(
[name] => OfferLM
[desc] => Description on the scheme
[no] => 4
[$$hashKey] => 01R
)
)
[$$hashKey] => 05V
)
[1] => stdClass Object
(
[sku] => 02
[name] => Product 2
[price] => 500
[quantity] => 1
[stock] => 400
[scheme] => Array
(
[0] => stdClass Object
(
[name] => offerAB
[desc] => Description on the scheme
[no] => 6
[$$hashKey] => 01W
)
[1] => stdClass Object
(
[name] => offerXY
[desc] => Description on the scheme
[no] => 7
[$$hashKey] => 01X
)
[2] => stdClass Object
(
[name] => OfferPQ
[desc] => Description on the scheme
[no] => 3
[$$hashKey] => 01Y
)
[3] => stdClass Object
(
[name] => OfferLM
[desc] => Description on the scheme
[no] => 8
[$$hashKey] => 01Z
)
)
[$$hashKey] => 05W
)
)
[qty] => 3
)
I want to print value of sku , name, price using foreach loop
Since i m new to it i first started printing a single value
echo $data->items->arr[0]->sku;
Notice: Trying to get property of non-object getting this error
but i want to print the values in foreach please help!
Items is a property of the main object, and in itself is an array. This is what you're after:
foreach($data->items as $d) {
echo $d->name, '<br />', $d->sku, '<br />', $d->price;
}
If you want to access one of those element without a loop, you need to provide the array index, for example:
echo $data->items[0]->name
the easy way for you is convert object to array
function array2object($array) {
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
}
else { $obj = $array; }
return $obj;
}
function object2array($object) {
if (is_object($object)) {
foreach ($object as $key => $value) {
$array[$key] = $value;
}
}
else {
$array = $object;
}
return $array;
}
// example:
$array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four');
$obj = array2object($array);
print $obj->one; // output's "two"
$arr = object2array($obj);
print $arr['foo']; // output's bar
foreach($data['items'] as $item) {
echo $item['sku'].PHP_EOL
echo $item['name'].PHP_EOL
echo $item['price'].PHP_EOL;
}

How to iterate through a nested stdClass? [duplicate]

This question already has answers here:
stdClass object and foreach loops
(5 answers)
Closed 4 months ago.
I have an object like this:
stdClass Object
(
[_count] => 10
[_start] => 0
[_total] => 37
[values] => Array
(
[0] => stdClass Object
(
[_key] => 50180
[group] => stdClass Object
(
[id] => 50180
[name] => CriticalChain
)
)
[1] => stdClass Object
(
[_key] => 2357895
[group] => stdClass Object
(
[id] => 2357895
[name] => Data Modeling
)
)
[2] => stdClass Object
(
[_key] => 1992105
[group] => stdClass Object
(
[id] => 1992105
[name] => SQL Server Users in Israel
)
)
[3] => stdClass Object
(
[_key] => 37988
[group] => stdClass Object
(
[id] => 37988
[name] => CDO/CIO/CTO Leadership Council
)
)
[4] => stdClass Object
(
[_key] => 4024801
[group] => stdClass Object
(
[id] => 4024801
[name] => BiT-HR, BI & IT Placement Agency
)
)
[5] => stdClass Object
(
[_key] => 37845
[group] => stdClass Object
(
[id] => 37845
[name] => Israel Technology Group
)
)
[6] => stdClass Object
(
[_key] => 51464
[group] => stdClass Object
(
[id] => 51464
[name] => Israel DBA's
)
)
[7] => stdClass Object
(
[_key] => 66097
[group] => stdClass Object
(
[id] => 66097
[name] => SQLDBA
)
)
[8] => stdClass Object
(
[_key] => 4462353
[group] => stdClass Object
(
[id] => 4462353
[name] => Israel High-Tech Group
)
)
[9] => stdClass Object
(
[_key] => 4203807
[group] => stdClass Object
(
[id] => 4203807
[name] => Microsoft Team Foundation Server
)
)
)
)
I need to get the id and name in an HTML table, but I seem to have a hard time iterating through this object. TIA. I understand that I need to get to the Values Array, and then to the group object, but I trip over the transitions between object and array and foreach vs index based iteration.
For example I tried this:
foreach ($res as $values) { print "\n"; print_r ($values); }
It iterates trough the object, but it also gives me useless
10 0 37
echo "<table>"
foreach ($object->values as $arr) {
foreach ($arr as $obj) {
$id = $obj->group->id;
$name = $obj->group->name;
$html = "<tr>";
$html .= "<td>Name : $name</td>";
$html .= "<td>Id : $id</td>";
$html .= "</tr>";
}
}
echo "</table>";
Since this is the top result in Google if you search for iterate over stdclass it may be helpful to answer the question in the title:
You can iterate overa stdclass simply by using foreach:
$user = new \stdClass();
$user->flag = 'red';
foreach ($user as $key => $value) {
// $key is `flag`
// $value is `red`
}
function objectToArray( $data )
{
if ( is_object( $data ) )
$d = get_object_vars( $data );
}
Convert the Object to array first like:
$results = objectToArray( $results );
and use
foreach( $results as result ){... ...}
I know it's an old post , but for sake of others:
when working with stdClass you should use Reflections:
$obj = new ReflectionObject($object);
$propeties = $obj->getProperties();
foreach($properties as $property) {
$name = $property->getName(); <-- this is the reflection class
$value = $object->$name; <--- $object is your original $object
here you need to handle the result (store in array etc)
}
foreach($res->values as $value) {
print_r($value);
}

Categories