多维数组循环

时间:2014-03-13 11:03:55

标签: php arrays

假设我们有一个这样的数组:

括号是键(主要是字符串),值大部分都是数组,直到最后一个值。

[meas1] => array
(

  [test1] => array
  (
    [computername1] => array
    (
      [0] => 2
      [1] => 5
      [2] => 8
    )
  )

)
[meas2] => array
(

  [test1] => array
  (
    [computername1] => array
    (
      [0] => 2
      [1] => 6
    )
  )
  [test2] => array
  (
    [computername1] => array
    (
      [0] => 4
      [1] => 9
    )
    [computername2] => array
    (
      [0] => 9
    )
  )

)

我试图通过使用类似下面的foreach来迭代它们,但是我得到了计算机键和其他键的'Array'。

foreach($graph_array as $measurement => $test)
    {

      $xml .= "<test>";
      $xml .= XML_value("name",$test);
      $xml .= XML_value("mname",$measurement);
    foreach($test as $sname => $asd)
      {
      $xml .= "<site>";
      $xml .= XML_value("name",key($sname));
      foreach($asd as $value)
        {
        $xml .= XML_value("value",$value);
        }
      $xml .= "</site>";
      }
    $xml .= "</test>";
    }

如何处理这些multidimensinal数组以创建这样的结果:

<test>
  <name>test1</name>
  <mname>meas1</mname>
  <site>
    <name>computername1</name>
      <value>2</value>
      <value>5</value>
      <value>8</value>
  </site>
</test>
<test>
.
.
.
</test>

etc

1 个答案:

答案 0 :(得分:1)

foreach($graph_array as $measurement => $tests)
{
    foreach($tests as $test => $computers)
    {
        $xml .= "<test>";
        $xml .= XML_value("name", $test);
        $xml .= XML_value("mname", $measurement);
        foreach($computers as $sitename => $values)
        {
            $xml .= "<site>";
            $xml .= XML_value("name", $sitename);
            foreach($values as $index => $value)
            {
                $xml .= XML_value("value", $value);
            }
            $xml .= "</site>";
        }
        $xml .= "</test>";
    }
}