我正在创建一个页面,用户可以在其中为他们使用的IP地址命名(反向DNS)。这些地址在路由器端口(接口)上配置,并在其上配置相同的UserId以使它们分开。路由器端口可以同时具有IPv4和IPv6地址。这是一个创建PortCollection的函数,其中每个端口都有一组IP地址对象:
public function testfunction() {
$this->portCollectionMapper->fetch($this->portCollection);
foreach($this->portCollection as $port) {
foreach(['v4', 'v6'] as $protocol) {
$this->addressMapper->fetch($port, $protocol);
}
}
}
此函数使用Port实例填充portCollection。然后,对于每个协议,addressMapper都会获取$ port的所有地址。
var_dump($ this-> portCollection)最终会是这样的:
object(PortCollection)#12 (2) {
["id":protected]=>
int(1000)
["ports":protected]=>
array(10) {
[0]=>
object(Port)#28 (6) {
["id":protected]=>
int(2280)
["addresses":protected]=>
array(2) {
["v4"]=>
array(1) {
[0]=>
object(IPv4Address)#40 (4) {
["id":protected]=>
int(863)
["address":protected]=>
string(13) "1.1.1.0"
["prefixLen":protected]=>
int(31)
}
}
["v6"]=>
array(1) {
[0]=>
object(IPv6Address)#42 (5) {
["id":protected]=>
int(478)
["address":protected]=>
string(39) "fe80:bc07::"
["prefixLen":protected]=>
int(64)
}
}
}
}
[1]=>
object(Port)#27 (6) {
["id":protected]=>
int(2302)
["addresses":protected]=>
array(1) {
["v6"]=>
array(1) {
[0]=>
object(IPv6Address)#39 (5) {
["id":protected]=>
int(488)
["address":protected]=>
string(39) "fe80:bc08::"
["prefixLen":protected]=>
int(64)
}
}
}
}
乍一看,这看起来并不那么糟糕。我为每个端口分配了所有IP地址对象。但是,对于我正在创建的页面,我希望将所有IPv4和IPv6地址分开。要做到这一点,我必须再次遍历一切(看起来确实很糟糕):
$ipv4addresses = $ipv6addresses = [];
foreach($this->portCollection as $port) {
foreach($port as $addresses) {
foreach($addresses as $address) {
if($address instanceof IPv4Address) {
$ipv4addresses[] = $address;
} else {
$ipv6addresses[] = $address;
}
}
}
}
因此,我的问题是:我怎样才能执行此循环一次,获取地址然后将所有IPv4和IPv6对象分开?