1
votes

Struggling to get my head around these MD Arrays so hoping someone can help. I have a 'config' file that looks like:

$clusters = array(
    "clustera" => array(
        '101',
        '102',
        '103',
        '104',
        '105',
        '106',
        '107',
        '108'
    ),
    "clusterb" => array(
        '201',
        '202',
        '203',
        '204',
        '205',
        '206',
        '207',
        '208'
    ),
    "clusterc" => array(
        '301',
        '302',
        '303',
        '304'
    ),
    "clusterd" => array(
        '401',
        '402',
        '403',
        '404'
    )
);

I then need to create a function that prints the keys of the first level array, followed by the values of the second level. As well as being a practical problem for me right now, I think knowing the solution would probably cement the fragmented pieces of my brain :)

So the output should be something like (to be wrapped in some html stuff but, for now):

clustera 101 102 103 104 105 106 107 108 clusterb 201 202 203 204 205 206 207 208 etc etc

Thanks!

1

1 Answers

2
votes

This is a simple nested foreach loop:

// Outer loop prints cluster name as array key
foreach ($clusters as $cluster => $array) {
  echo "$cluster: ";
  // Inner loop prints space-separated array values
  foreach ($array as $val) {
    echo "$val ";
  }
}

This can also be done without an inner loop, using implode() if you really only need space-separated values:

// Outer loop prints cluster name as array key
foreach ($clusters as $cluster => $array) {
  // implode() with a space, and add a trailing space to separate the clusters....
  echo "$cluster: " . implode(" ", $array) . " ";
}

// clustera: 101 102 103 104 105 106 107 108 clusterb: 201 202 203 204 205 206 207 208 clusterc: 301 302 303 304 clusterd: 401 402 403 404