【发布时间】: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