在PHP中从Array / Object中提取数据?

时间:2015-03-10 09:37:55

标签: php

首先,我是PHP和编码的新手,所以这可能是一个非常明显的答案。

我目前正在使用Strava API,并且我尝试从以下API调用的结果中提取数据/对象中的数据:

$recentactivities = $api->get('athlete/activities', array('per_page' => 100));

返回:

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] =>
   )

重复最近的活动。

我尝试提取average_heartrate,我可以使用以下内容为单个对象执行此操作:

$recentactivities[1]->average_heartrate;

但我想从数组中提取average_heartrate的所有实例。我曾尝试使用foreach声明,但说实话,我不知道从哪里开始。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

实际上,你确实可以使用foreach循环非常简单:

foreach($myArray as $obj){
  //$obj is an object so:
  if(isset($obj->average_heartrate)){
     echo $obj->average_heartrate;
  }
}

答案 1 :(得分:0)

使用此代码,您可以使用对象遍历数组并将所需数组保存在数组中,以便您可以进一步使用它。

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