php read from array inside class - php

when i use print_r for the response from API URL i got the following result:
stdClass Object(
[Messages] => Array
(
[0] => stdClass Object
(
[MessageID] => 990950058
[Recipient] => 966000000000
[Status] => Queued
)
[1] => stdClass Object
(
[MessageID] => 990950059
[Recipient] => 966500000000
[Status] => Queued
)
)
[NumberOfUnits] => 1
[Cost] => 0.00000
[Balance] => 2.89050
[TimeCreated] => 2016-11-10 14:03:49
[CurrencyCode] => SAR
)
the problem is i want to make a loop to read the values for MessageID
how i can do it?

so simple use foreach is used to loop through each key/value pair
foreach($your_variable->Messages as $row)
{
echo $row->MessageID;
}

Related

php parse array in object detail

I got stuck on parsing array in my php object
stdClass Object
(
[result] => stdClass Object
(
[details] => Array
(
[0] => stdClass Object
(
[account] =>
[address] => add1
[category] => receive
[amount] => 1100
[label] =>
[vout] => 1
)
[1] => stdClass Object
(
[account] =>
[address] => add2
[category] => receive
[amount] => 11600
[label] =>
[vout] => 2
)
[2] => stdClass Object
(
[account] =>
[address] => add3
[category] => receive
[amount] => 1000
[label] =>
[vout] => 4
)
)
)
)
So how I can fetch all details indexes 0,1,2 etc
So, you could just iterate over details as below:
foreach($your_variable->result->details as $current_detail){
echo $current_detail->account;
// other code here
}
Your data is object if you converto to array u can simply do it
$array=json_decode(json_encode($data),true);
print_r($array);
If just one details key
$array=json_decode(json_encode($data),true)
print_r($array['result']['details']);

Looping through JSON object properties

I'm totally newbie what comes to programming so i'm not even quite sure if my terms are right but i would like to get some hints and tips what is best practice to loop through JSON object? Let's say i want all game names from following JSON print_r output.
stdClass Object
(
[_total] => 555
[_links] => stdClass Object
(
[self] => https://api.twitch.tv/kraken/games/top?limit=2&offset=0
[next] => https://api.twitch.tv/kraken/games/top?limit=2&offset=2
)
[top] => Array
(
[0] => stdClass Object
(
[viewers] => 86386
[channels] => 1159
[game] => stdClass Object
(
[name] => League of Legends
[_id] => 21779
[giantbomb_id] => 24024
[box] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-52x72.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-136x190.jpg
[large] => http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-272x380.jpg
)
[logo] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-60x36.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-120x72.jpg
[large] => http://static-cdn.jtvnw.net/ttv-logoart/League%20of%20Legends-240x144.jpg
)
[_links] => stdClass Object
(
)
)
)
[1] => stdClass Object
(
[viewers] => 17288
[channels] => 162
[game] => stdClass Object
(
[name] => Hearthstone: Heroes of Warcraft
[_id] => 138585
[giantbomb_id] => 42033
[box] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-52x72.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-136x190.jpg
[large] => http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-272x380.jpg
)
[logo] => stdClass Object
(
[template] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-{width}x{height}.jpg
[small] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-60x36.jpg
[medium] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-120x72.jpg
[large] => http://static-cdn.jtvnw.net/ttv-logoart/Hearthstone%3A%20Heroes%20of%20Warcraft-240x144.jpg
)
[_links] => stdClass Object
(
)
)
)
)
)
I can access single line (not sure if this is best practise either):
$OBJ->method()->top[0]->game->name;
But i'm more than clueless how to loop through all game names.
Any help much appreciated!
The "name"s are accessed using $OBJ->top[0]->game->name etc... So just foreach over the "top" array:
foreach($OBJ->top as $object) {
echo $object->game->name;
}
Create an empty array, loop the objects top array and fill your empty array:
$allgames=array();
foreach($OBJ->method()->top as $ob){
$allgames[] = $ob->game->name;
}
When you load your JSON string into PHP you can use:
json_decode($string_of_json, true);
The true flag will load it into an array you can loop through using, for example, foreach.

Store this as an object

SOLUTION:
Each of the keys ending :private had a __get() and toJSON() method which is needed to get the data from them as _propMap is private.
I'm using PayPal's PHP API to take payments from PayPal, and the data I get after a payment has been completed, comes back as this
Array
(
[PayPal\Common\PPModel_propMap] => Array
(
[id] => PAY-THEID
[create_time] => 2013-12-03T15:47:15Z
[update_time] => 2013-12-03T15:47:34Z
[state] => approved
[intent] => sale
[payer] => PayPal\Api\Payer Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[payment_method] => paypal
[payer_info] => PayPal\Api\PayerInfo Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[email] => my#email.com
[first_name] => Tom
[last_name] => Hart
[payer_id] => thePayerId
[shipping_address] => PayPal\Api\Address Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[line1] => 1 Main Terrace
[city] => Wolverhampton
[state] => West Midlands
[postal_code] => W12 4LQ
[country_code] => GB
)
)
)
)
)
)
[transactions] => Array
(
[0] => PayPal\Api\Transaction Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[amount] => PayPal\Api\Amount Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[total] => 0.33
[currency] => GBP
[details] => PayPal\Api\Details Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[subtotal] => 0.11
[tax] => 0.11
[shipping] => 0.11
)
)
)
)
[description] => Payment description
[item_list] => PayPal\Api\ItemList Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[items] => Array
(
[0] => PayPal\Api\Item Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[name] => Flowers
[price] => 0.11
[currency] => GBP
[quantity] => 1
)
)
)
)
)
[related_resources] => Array
(
[0] => PayPal\Api\RelatedResources Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[sale] => PayPal\Api\Sale Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[id] => 9L998852HN614082X
[create_time] => 2013-12-03T15:47:15Z
[update_time] => 2013-12-03T15:47:34Z
[state] => completed
[amount] => PayPal\Api\Amount Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[total] => 0.33
[currency] => GBP
)
)
[parent_payment] => PAY-4S184757A49956741KKO72AY
[links] => Array
(
[0] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/payments/sale/9L998852HN614082X
[rel] => self
[method] => GET
)
)
[1] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/payments/sale/abc/refund
[rel] => refund
[method] => POST
)
)
[2] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-abc
[rel] => parent_payment
[method] => GET
)
)
)
)
)
)
)
)
)
)
)
[links] => Array
(
[0] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/payments/payment/abc
[rel] => self
[method] => GET
)
)
)
)
)
I want to convert parts of that (shipping_address being one of them) to a json object (using json_encode/decode(), and store it in my database so in the admin section I can view the address so I know where to send things, however, I can't convert that to a json object, it just returns {}. How can I store these details in my database to view them later?
EDIT:
Json_encode code
$db['address'] = json_encode((array) $dets->payer->payer_info->shipping_address);
var_dump(json_last_error());
$db['payerId'] = $dets->payer->payer_info->payer_id;
$db['prices'] = json_encode((array) $dets->transations[0]->amount);
var_dump(json_last_error());
$db['description'] = $dets->transations[0]->description;
$db['items'] = json_encode((array) $dets->transations[0]->item_list->items);
var_dump(json_last_error());
$db['links'] = json_encode((array) $dets->related_resources[0]->sale->links);
var_dump(json_last_error());
The output of the $db array is
Array
(
[userId] => 10
[paymentId] => PAY-4VC71851RJ180032AKKPAB3Y
[state] => approved
[address] => {"\u0000PayPal\\Common\\PPModel\u0000_propMap":{"line1":"1 Main Terrace","city":"Wolverhampton","state":"West Midlands","postal_code":"W12 4LQ","country_code":"GB"}}
[payerId] => P77LD9M7MUQN2
[prices] => []
[description] =>
[items] => []
[links] => []
)
So some are getting encoded, some arnt.
This was also bothering me for a while and I struggled to find a straightforward answer. I'm using the current PHP REST STK and in the sample ExecutePayment.php file saw something like this:
// Execute the payment
// (See bootstrap.php for more on `ApiContext`)
$result = $payment->execute($execution, $apiContext);
echo "<html><body><pre>";
var_dump($result);
echo "</pre><a href='../index.html'>Back</a></body></html>";
As noted, the $result object is not very helpful to navigate. You can't directly encode the object as PayPal is doing some crazy stuff on their own in the SDK. As noted, the solution is to use the toJSON() method from the PPModal class to convert that object into JSON directly:
$result = $payment->execute($execution, $apiContext);
$array = $result->toJSON();
echo '<pre>';
print_r($array);
echo '</pre>';
I hope that's a little clearer to somebody.
I think the problem you are having with some values "not being encoded" is that some of your variable references are wrong.
For example, you are trying to encode:
$dets->transations[0]->amount
Whereas, I think you need to get that value from:
$dets->transactions[0]['_propMap:PayPal\Common\PPModel:private']['amount']
You have similar issue for most of your variable references.

Freshbooks API show details

I am using the php library from here and I have a small problem.
To get some info for a invoice 118868, I can do this
<?php
$invoice_id=118868;
$invoice=$freshbooks->invoiceGet($invoice_id);
print_r($invoice);
?>
This is the output for print_r
Class Object ( [#attributes] => stdClass Object ( [status] => ok ) [invoice] => stdClass Object ( [invoice_id] => 00000219023 [estimate_id] => stdClass Object ( ) [number] => 8822 [client_id] => 83 [contacts] => stdClass Object ( [contact] => stdClass Object ( [contact_id] => 0 ) ) [recurring_id] => stdClass Object ( ) [organization] => Jimmy Thwart [first_name] => stdClass Object ( ) [last_name] => stdClass Object ( ) [p_street1] => stdClass Object ( ) [p_street2] => stdClass Object ( ) [p_city] => stdClass Object ( ) [p_state] => stdClass Object ( ) [p_country] => stdClass Object ( ) [p_code] => stdClass Object ( ) [po_number] => 10002 [status] => sent [amount] => 16.90 [amount_outstanding] => 16.90 [paid] => 0.00 [date] => 2013-01-31 00:00:00 [notes] => stdClass Object ( ) [terms] => Your slot can only be secured upon payment. Any reservation made before payment will only be guaranteed for 2 days. [discount] => 0 [url] => https://example.freshbooks.com/view/vgPb2TNGCR7n8JV [auth_url] => https://example.freshbooks.com/invoices/219023 [links] => stdClass Object ( [client_view] => https://example.freshbooks.com/view/vgPb2TNGCR7n8JV [view] => https://example.freshbooks.com/invoices/219023 [edit] => https://example.freshbooks.com/invoices/219023/edit ) [return_uri] => stdClass Object ( ) [updated] => 2013-01-31 02:25:13 [currency_code] => SGD [language] => en [vat_name] => stdClass Object ( ) [vat_number] => stdClass Object ( ) [folder] => active [staff_id] => 1 [lines] => stdClass Object ( [line] => stdClass Object ( [line_id] => 1 [name] => Lady 1pax [description] => Services (1 pax) [unit_cost] => 16.90 [quantity] => 1 [amount] => 16.90 [tax1_name] => stdClass Object ( ) [tax2_name] => stdClass Object ( ) [tax1_percent] => 0 [tax2_percent] => 0 [compound_tax] => 0 [type] => Item ) ) [gateways] => stdClass Object ( [gateway] => stdClass Object ( [name] => PayPal ) ) ) )
I hope the output can only be the URL and not this whole chunk of code.
Output wanted:
https://example.freshbooks.com/view/vgPb2TNGCR7n8JV
However, it lists all information of the invoice. How do I get only the invoice URL?
Well, using the output of your code, you can see what the elements of $invoice are. Use the one that you need.
Invoice is an instane of a class. You should treat it like all instances.
To get URL value you can do the next:
<?php
$invoice_id=118868;
$invoice=$freshbooks->invoiceGet($invoice_id);
print $invoice->url;
?>
or there's another possible value you're looking for:
<?php
$invoice_id=118868;
$invoice=$freshbooks->invoiceGet($invoice_id);
print $invoice->links->client_view;
?>
According to official API doc <url> is not supporting any more, so you should use <links> "element to provide your customers with direct links to the invoice for editing, viewing by the client and viewing by an administrator."

PHP How To Merge An Array Of Objects WIth An Array Of Arrays

First, sorry for the lengthly explanation. I have two arrays in PHP. The first array is an array of objects. The second array is an array of arrays. Basically, I want to loop through, and merge the object with its matching array, and return a merged object.
See the following print_r() of the array of objects structures:
Array
(
[0] => stdClass Object
(
[gear] => helloworld
[status] => running
[started] => 40 Minutes Ago
[start] => index.js
[route] => 127.0.0.1:3000
[parameters] => Array
(
)
)
[1] => stdClass Object
(
[gear] => test
[status] => stopped
[started] =>
[start] => index.js
[route] =>
[parameters] => Array
(
)
)
[2] => stdClass Object
(
[gear] => test2
[status] => stopped
[started] =>
[start] => index.js
[route] =>
[parameters] => Array
(
[0] => first
[1] => second
[2] => third
)
)
)
See the following print_r() of the array of arrays structures:
Array
(
[0] => Array
(
[gear] => helloworld
[machine_id] => E6z5ekvQ
[created_by] => 10010
[modified_by] => 10010
[created] => 2011-09-22T16:30:11-07:00
[modified] => 2011-09-22T16:30:11-07:00
)
[1] => Array
(
[gear] => test
[machine_id] => E6z5ekvQ
[created_by] => 10010
[modified_by] => 10010
[created] => 2011-09-22T16:44:25-07:00
[modified] => 2011-09-22T16:44:25-07:00
)
[2] => Array
(
[gear] => test2
[machine_id] => E6z5ekvQ
[created_by] => 10010
[modified_by] => 10010
[created] => 2011-09-22T16:45:43-07:00
[modified] => 2011-09-22T16:45:43-07:00
)
)
So basically the matching key for both is gear. So we should match the gear from the first object, with the second gear in the array, and return something like:
stdClass Object
(
[gear] => helloworld
[status] => running
[started] => 40 Minutes Ago
[start] => index.js
[route] => 127.0.0.1:3000
[parameters] => Array
(
)
[machine_id] => E6z5ekvQ
[created_by] => 10010
[modified_by] => 10010
[created] => 2011-09-22T16:30:11-07:00
[modified] => 2011-09-22T16:30:11-07:00
)
Notice, that the gear is merged into one property of the object, obviously gear does not appear twice. Ideas?
If you could index the array by gear or some unique value, it would be a lot easier.
$indexed = array();
// create an array using 'gear' as the index
foreach($arrayValue as $value) {
$indexed[$value['gear']] = $value;
}
// loop over each object
foreach($objectArray as $obj) {
$value = $indexed[$obj->gear]; // find the corresponding array
foreach($value as $name => $val) {
$obj->$name = $val; // assign each array index/value pair to the object
}
}
If possible to get your code to return the array with the index by default, you can remove the first foreach loop.
Hope that helps.

Categories