php - 从域名列表中创建排序数组 [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;
}
}
推荐阅读
- python-3.x - TensorFlow 对象检测 API - GitHub
- yii2 - Urlmanager中的yii2冲突
- reactjs - 如何使用带有 strophe 库的 ejabber 服务器将消息发送到群聊?
- node.js - 使用 express + bootstrap 模式时 POST 不起作用
- amazon-web-services - 配置 Envoy 以使用 AWS ECS 和 Route53 生成的 SRV 记录
- java - 在Android中按下按钮之前播放音频
- java - DateTime("2019-02-16T10:00:00+08:00") 转换为具有偏移值的本地日期时间
- python - 无法删除 Powerpoint 幻灯片?
- jquery - jQuery On Click 功能只工作一次
- maven - 如果打包设置为 pom,wildfly.maven.plugin 不会部署任何内容