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语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?