如何用PHP构建数组

时间:2017-05-17 05:28:24

标签: php arrays ip

我想将IP段转换为数组,

IP段:218.240.0.0 - 218.240.255.255 数组

Array(
[218]=>Array([240]=>Array([0]=>Array([0]=>Array([xxx]=>CN))))
[218]=>Array([241]=>Array([0]=>Array([0]=>Array([xxx]=>CN))))
)

这是我尝试编写相关代码的原因,

<?php
$startip = '218.240.0.0';
$endip = '218.241.255.255';
$sip = explode('.', $startip);
$eip = explode('.', $endip);
$tb =array('');
for($i = 0;$i <= ($eip[1] - $sip[1]);$i++){
    $ip2 = $sip[1] + $i;                                       
    $tb[$sip[0]][$ip2][] = array('xxx' => 'CN');
}
print_r($tb);

1 个答案:

答案 0 :(得分:0)

您可能希望使用ip2long()long2ip(),即:

$ip_range = [];
$start = ip2long ("218.240.0.0");
$end = ip2long("218.240.255.255");
while ($start <= $end) {
    $ip_range[] = long2ip($start++);
}

print_r($ip_range);

/*
    [0] => 218.240.0.0
    [1] => 218.240.0.1
    [2] => 218.240.0.2
    [3] => 218.240.0.3
    [4] => 218.240.0.4
    [5] => 218.240.0.5
    [6] => 218.240.0.6
    [7] => 218.240.0.7
    [8] => 218.240.0.8
    [9] => 218.240.0.9
    ...
*/