我正在使用FedEx的API来查找他们商店的"投递"位置,然后我将使用地图API(Google)显示这些位置。
API 正在工作,但是我遇到了麻烦,因为我不熟悉面向对象的数组。
我想将数组中的值存储为唯一变量,以便将它们传递给我的地图 API。
我正在尝试完成如下任务:
<?php
// MY "IDEAL" solution - any other ideas welcome
// (yes, reading up on Object Oriented PHP is on the to-do list...)
$response = $client ->fedExLocator($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$response -> BusinessAddress -> StreetLines[0] = $location_0;
$response -> BusinessAddress -> StreetLines[1] = $location_1;
$response -> BusinessAddress -> StreetLines[2] = $location_2;
}
?>
工作联邦快递代码示例:
<?php
$response = $client ->fedExLocator($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
echo 'Dropoff Locations<br>';
echo '<table border="1"><tr><td>Streetline</td><td>City</td><td>State</td><td>Postal Code</td><td>Distance</td></tr>';
foreach ($response -> DropoffLocations as $location)
{
if(is_array($response -> DropoffLocations))
{
echo '<tr>';
echo '<td>'.$location -> BusinessAddress -> StreetLines. '</td>';
echo '<td>'.$location -> BusinessAddress -> PostalCode. '</td>';
echo '</tr>';
}
else
{
echo $location . Newline;
}
}
echo '</table>';
}
?>
好的,据我所知,$response
对象有两个成员:$response->HighestSeverity
,这是一个字符串,$response->DropoffLocations
是一个数组。 $response->DropoffLocations
只是一个阵列,表面上没有什么花哨的。您可以用方括号引用其条目(例如 $response->DropoffLocations[0]
等),或者,就像他们所做的那样,foreach
一起走过它.
关于数组的唯一"面向对象",除了它是对象的成员之外,是它的条目是对象,而不是简单的值。
结果,您将索引放在错误的位置(并且完全丢失了DropoffLocations
)。而不是,例如,这个:
$response -> BusinessAddress -> StreetLines[0] = $location_0;
您应该$response->DropoffLocations
本身编制索引,然后从每个条目中提取成员变量,如下所示:
$response -> DropoffLocations[0] -> BusinessAddress -> StreetLines = $location_0;
不过,请注意@PeterGluck的评论。您不太可能将该值设置为任何值。