McJohnson McJohnson - 1 month ago 6
PHP Question

Accessing elements in a multidimensional array in 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?

Answer

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."\n";
    }
}

output:

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

exacly what you asked for.