First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}
Related
I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].
I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";
I have the following array structure, this is the array passed in to $response
Array
(
[inbox] => Array
(
[0] => Array
(
[location] => 3
[ID] => 8ba84195fe79a89af1a4b5bd8c280621
[smsc_number] => +44******
[sent] => 2013-02-25 14:57:20
[coding] => Default GSM alphabet (no compression)
[remote_number] => +447****
[status] => Read
[body] => Yeppp
)
)
[outbox] => Array
(
[0] => Array
(
[location] => 2
[ID] => d22c4368fadd64e98fab64acb6b8fa34
[reference_number] => 1
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => *****
[status] => Sent
[body] => Test
)
[1] => Array
(
[location] => 0
[ID] => f0c05e8dd2578d16d73bf5dbcf2ec3e6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
[2] => Array
(
[location] => 1
[ID] => d7537acb1b3994ecc11369bac46c4bb6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****3
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
)
)
I'm only interested in the body of the inbox array. I thought I could just do two loops to get this, or just do $response[0] but it doesn't seem to work. Heres what I have:
$response = $sms->Get();
foreach ($response[0] as $value) {
foreach ($response as $value1) {
echo($value1['body']);
}
}
I'm obviously doing something very stupid - Any help would be really appreciated
Try this
foreach ($response['inbox'] as $inb) {
echo($inb['body']); }
I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.
I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!
You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}