我的API调用给了我以下代码:
Array ( [ABC01] =>
Array ( [0] =>
stdClass Object (
[hostid] => 12345
[location_lat] => 40
[location_lon] => 70
[site_address_a] => Hello World Blvd
[site_address_b] => Foo 100
[site_city] => Redmond
[site_state] => Washington
[site_country] => USA ) )
最终,我试图解决这个问题:
Array ( [ABC01] =>
[hostid] => 12345
[location_lat] => 40
[location_lon] => 70
[site_address_a] => Hello World Blvd
[site_address_b] => Foo 100
[site_city] => Redmond
[site_state] => Washington
[site_country] => USA ) )
我有近三个foreach循环,我仍然有点迷失。我知道必须有一个简单的方法,但我不太熟悉PHP。我只是用get_object_vars来获取位置对象:
foreach($getLocations as $key => $value) {
print_r(get_object_vars($value[0]));
}
我是否在正确的轨道上?然后我很困惑如何将它与主机名(ABC01)联系起来,因为那是我想输出的,而不是hostid。感谢您的帮助,这个PHP noob赞赏它。
答案 0 :(得分:1)
如果您想要的输出实际上是这样的:
array(1) {
["ABC01"]=>
array(8) {
["hostid"]=>
int(12345)
["location_lat"]=>
int(40)
["location_lon"]=>
int(70)
["site_address_a"]=>
string(16) "Hello World Blvd"
["site_address_b"]=>
string(7) "Foo 100"
["site_city"]=>
string(7) "Redmond"
["site_state"]=>
string(10) "Washington"
["site_country"]=>
string(3) "USA"
}
}
然后是的,我认为你在正确的轨道上,这应该产生它:
$output = [];
foreach($data as $key => $value) {
$output[$key] = get_object_vars($value[0]);
}
var_dump($output);
请注意,这假定单个' 0'每个主机名的元素。
然后我对如何将其与主机名(ABC01)联系起来感到困惑 因为那是我想输出的,而不是hostid
主机名是foreach中的$ key,它用于指定输出数组的键。