从域名列表中创建排序数组[PHP]



我正试图根据域的子域将域列表转换为嵌套数组。一开始这似乎微不足道,但我的小脑袋在挣扎。

输入:

example.com
www.example.com
email.example.com
1.email.example.com
example.net

预期输出。

$array = array(
"com" => array(
"example",
"example" => array("www","email"=> "1")),
"net" => "example",
);

我可以用以下代码来接近:

$a = 'a.google.com';
$b = 'b.google.com';
$c = 'c.google.com';
$a1 = '1.a.google.com';
$a2 = '5.2.a.google.com';
$a3 = '3.a.google.com';
$d = [$a,$b,$c,$a1,$a2,$a3];
$result = [];
foreach ($d as $domain){

$fragments = array_reverse( explode( '.', $domain ));

for ($x = 0; $x <= count($fragments)-1; $x++) {         
if (!is_array($result[$x])){ $result[$x] = [];}
array_push($result[$x], $fragments[$x]);
}
}
echo '<pre>';
var_dump($result);
echo '</pre>';

尽管这并没有嵌套数组,而且如果没有某种可变数组构造,我看不出如何访问正确的数组来将数据推送到其中。哈尔普!:P

在这里,我检查分解的数组是否大于2个元素,如果是,则取最后一个元素作为要添加到结果中的值:

foreach($d as $domain) {
$path  = array_reverse(explode('.', $domain));

if(count($path) > 2) {
$value = array_pop($path);
} else {
$value = false;
}
$temp =& $result;

foreach($path as $key) {
$temp =& $temp[$key];
}
if($value) {
$temp[] = $value;
}
}

最新更新