stdClass Object foreach PHP loop - php

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.

Related

PHP Soap Request foreach

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

How to print the values from an array return by a json response?

I am trying to print a json array into its values I have the following array after json decode and i need to print it in a loop as it has many items.
For e.g i have to print the value firstName, lastName ,how will i print it.
stdClass Object ( [content] => Array ( [0] => stdClass Object ( [id] => 5 [firstName] => Ali [lastName] => S [profilePhotoUrl] => https://prn-spe-images.s3-ap-southeast-1.amazonaws.com/user-profiles/5.jpg [handle] => aliya ) [1] => stdClass Object ( [id] => 69 [handle] => hhtc ) ) [last] => 1 [totalPages] => 1 [totalElements] => 2 [numberOfElements] => 2 [first] => 1 [sort] => [size] => 10 [number] => 0 )
Sample code i have done :
$arrayl = gettviewers($post->id,10);
foreach($arrayl as $valuel) {
print $value1->content->firstName;
}
But it is not printing any value.
### Full working code from the below answers: ###
Helper file:
####### --- Get live viwers list for each broadcast --- ########
if ( ! function_exists('gettviewers'))
{
function gettviewers($broId,$size){
$CI =& get_instance();
$url = API_SERVER.'broadcasts/public/'.$broId.'/top-viewers?size='.$size;
$json = json_decode(file_get_contents($url), true);
return $json;
}
}
In the view:
$arrayl = gettviewers($post->id, WI_LIVEUSERSIZE);
foreach($arrayl as $value1)
{
print $value1[0][firstName];
}
Foreach 'takes' every element of a object or an array. So when you do foreach your $value1 isn't
stdClass Object ( [content] => Array ( [0] => stdClass Object ( [id] => 5 [firstName] => Ali [lastName] => S [profilePhotoUrl] => https://prn-spe-images.s3-ap-southeast-1.amazonaws.com/user-profiles/5.jpg [handle] => aliya ) [1] => stdClass Object ( [id] => 69 [handle] => hhtc ) ) [last] => 1 [totalPages] => 1 [totalElements] => 2 [numberOfElements] => 2 [first] => 1 [sort] => [size] => 10 [number] => 0 )
but is
[content] => Array ( [0] => stdClass Object ( [id] => 5 [firstName] => Ali [lastName] => S [profilePhotoUrl] => https://prn-spe-images.s3-ap-southeast-1.amazonaws.com/user-profiles/5.jpg [handle] => aliya ) [1] => stdClass Object ( [id] => 69 [handle] => hhtc ) ) [last] => 1 [totalPages] => 1 [totalElements] => 2 [numberOfElements] => 2 [first] => 1 [sort] => [size] => 10 [number] => 0
So your $value1 is already [content]. Also you should notice that [content] is an array so you have to do
$arrayl = gettviewers($post->id,10);
foreach($arrayl as $valuel) {
print $value1[0]->firstName;
}
or use second foreach loop inside the first one.
You can achieve this using json_decode
json_decode converts a valid JSON to a stdClass-Object.
Try this:
$arrayl = json_decode(gettviewers($post->id, 10));
foreach($arrayl as $value1)
{
print $value1->content->firstName;
}
try this
$arrayl = gettviewers($post->id,10);
if (is_object($arrayl)) {
// Gets the properties of the given object
// with get_object_vars function
$arrayl = get_object_vars($arrayl);
}
if (is_array($arrayl)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
$arrayl = array_map(__FUNCTION__, $arrayl);
}
else {
// Return array
return $arrayl;
}
var_dump($arrayl) or print_r($arrayl);
or
foreach($arrayl as $key=>$val){
echo $val->content[$key]
}
To print json_encoded array do this
$array=json_decode($data,true); //data is your json_encoded data
foreach($array as $key=>$value)
{
echo $key . ' ' . $value . PHP_EOL;
}
or just do
print_r($array);
after decoding it.

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

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