我有一个对象,我想从中显示一个值。
我的对象如下:
Array
(
[0] => Array
(
[0] => Orionstraat 11, 3235 TE Rockanje, Netherlands
)
[1] => Array
(
[0] => Woonkreek 56, 3206 GT Spijkenisse, Netherlands
)
[2] => Array
(
[0] => stdClass Object
(
[elements] => Array
(
[0] => stdClass Object
(
[distance] => stdClass Object
(
[text] => 25.2 km
[value] => 25195
)
[duration] => stdClass Object
(
[text] => 30 mins
[value] => 1796
)
[status] => OK
)
)
)
)
[3] => OK
)
我想在value
内返回distance
。
所以我这样做了:
foreach($distancedecoded as $route){
$distance = $route->elements->distance->value;
}
echo $distance;
但这没有显示,为什么会这样?
我也试过了:
$distance = $route[2]->elements->distance->value;
当我得到一个数组而不是一个对象时:
$distancedecoded = json_decode($getdistance, true);
foreach($distancedecoded as $route){
$distance = $route[2][0]['elements'][0]['distance']['value'];
$routearray[] = $route;
}
我收到了这些警告:
Warning: Illegal string offset 'elements' in /home/site/public_html/_extern/site/includes/getzip.php on line 105
Warning: Illegal string offset 'distance' in /home/site/public_html/_extern/site/includes/getzip.php on line 105
Warning: Illegal string offset 'value' in /home/site/public_html/_extern/site/includes/getzip.php on line 105
$distancedecoded
object(stdClass)#35 (4) {
["destination_addresses"]=>
array(1) {
[0]=>
string(45) "Orionstraat 11, 3235 TE Rockanje, Netherlands"
}
["origin_addresses"]=>
array(1) {
[0]=>
string(46) "Woonkreek 56, 3206 GT Spijkenisse, Netherlands"
}
["rows"]=>
array(1) {
[0]=>
object(stdClass)#36 (1) {
["elements"]=>
array(1) {
[0]=>
object(stdClass)#37 (3) {
["distance"]=>
object(stdClass)#38 (2) {
["text"]=>
string(7) "25.2 km"
["value"]=>
int(25195)
}
["duration"]=>
object(stdClass)#39 (2) {
["text"]=>
string(7) "30 mins"
["value"]=>
int(1796)
}
["status"]=>
string(2) "OK"
}
}
}
}
["status"]=>
string(2) "OK"
}
答案 0 :(得分:1)
$destination = $distancedecoded->destination_addresses[0];
$origin = $distancedecoded->origin_addresses[0];
$distance = $distancedecoded->rows[0]->elements[0]->distance->value;
$duration = $distancedecoded->rows[0]->elements[0]->duration->value;