打印好PHP'混合'多维数组

时间:2012-02-13 15:04:41

标签: php multidimensional-array

挣扎着绕过这些MD阵列,希望有人可以提供帮助。我有一个'config'文件,看起来像:

$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'
    )
);

然后我需要创建一个打印第一级数组的键的函数,然后是第二级的值。除了现在对我来说是一个实际问题,我认为知道解决方案可能会巩固我脑子里的碎片:)

所以输出应该是这样的(包含在一些html中,但是现在):

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

谢谢!

1 个答案:

答案 0 :(得分:2)

这是一个简单的嵌套foreach循环:

// 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 ";
  }
}

如果你真的只需要以空格分隔的值,那么使用implode()也可以在没有内循环的情况下完成:

// 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