【问题标题】:Create sorted array from a list of domain names [PHP]从域名列表中创建排序数组 [PHP]
【发布时间】:2020-11-24 16:51:09
【问题描述】:

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

输入:

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

【问题讨论】:

    标签: php arrays sorting dns subdomain


    【解决方案1】:

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

    【讨论】:

    • 谢谢!尽管当您拥有具有多个子域的域时,这种格式似乎会中断,例如 if $a = '1.22.a.google.com';那么结果数组(为便于阅读,采用 JSON 格式)为:{"com":{"google":{"a":{"22":["1"],"23":"1","2" :["5"],"24":"3"},"0":"b","1":"c"}}}。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多