首页 > 解决方案 > 从域名列表中创建排序数组 [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

标签: phparrayssortingdnssubdomain

解决方案


在这里,我检查分解后的数组是否大于 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;
    }
}

推荐阅读