www
www

Reputation: 596

Multi-dimensinal array loop

Assume we have an array like this:

The brackets are keys (mostly string) and the values are mostly array until the last value.

[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
    )
  )

)

I was trying to iterate through them by using foreach like the below, but however I am getting ´Array´ for the computername keys and the others.

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

How can I handle these multidimensinal arrays to create such a result:

<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

Upvotes: 1

Views: 53

Answers (1)

Jon
Jon

Reputation: 12992

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

Upvotes: 1

Related Questions