douxuanpa8298 2016-10-16 00:57
浏览 47
已采纳

在PHP中访问多维数组中的元素

I am trying to associate every subdomain, from a list, with its main domain name and I am doing this like so:

<?php

$main_domains = ['example.co.uk','example.com','example.org'];
$subdomains = ['sub.example.com','ftp.example.org','ftp.example.co.uk','mail.example.com'];

$results = [];
foreach ($subdomains as $subdomain) {
    foreach ($main_domains as $domain) {
        if (strpos($subdomain, $domain) !== false) {
            $results[$domain][] = $subdomain;
            continue;
        }
    }
}

Where in the end $results contains the following:

array(3) {
  ["example.com"]=>
  array(2) {
    [0]=>
    string(15) "sub.example.com"
    [1]=>
    string(16) "mail.example.com"
  }
  ["example.org"]=>
  array(1) {
    [0]=>
    string(15) "ftp.example.org"
  }
  ["example.co.uk"]=>
  array(1) {
    [0]=>
    string(17) "ftp.example.co.uk"
  }
}

However, I would now like to echo out the information like so:

<main domain> <sub domain>
<main domain> <sub domain>
...

i.e:

example.com sub.example.com
example.com mail.example.com
example.org ftp.example.org
example.co.uk ftp.example.co.uk

How can I do that?

  • 写回答

1条回答 默认 最新

  • doumao8355 2016-10-16 01:15
    关注

    most importantly is to set up the initial structure.

    $dom=array('example.co.uk'=>array('ftp.example.co.uk','zzz.example.co.uk'));
    
    foreach($dom as $domain=>$sub){
    
        foreach($sub as $s){
            echo $domain.' '.$s."
    ";
        }
    }
    

    output:

    example.co.uk ftp.example.co.uk
    example.co.uk zzz.example.co.uk

    exacly what you asked for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ /QT 内存权限的判断函数列举
  • ¥15 深度学习GFnet理解问题
  • ¥15 单细胞小提琴堆叠图代码
  • ¥80 LS dyna mpp并行报错
  • ¥50 升级strust2版本到2.3.15.1后使用ognl3.0.6.jar windows环境中没有问题,但部署到linux环境报错
  • ¥15 vue页面,node封装接口
  • ¥15 求TMS320F280039C工程模板!
  • ¥15 delphi+fastreport实现分组补空打印问题
  • ¥15 使用python把两台mysql数据库服务器数据导出和导入
  • ¥15 NodeBB论坛配置Apache Solr中文搜索引擎的详细教程