0

I have an array with a data structure like below

$array = array(
   'someKey' => array(
       'id' => 1,
       'string' => 'some key',
       'someKey2' => array(
            'id' => 1,
            'string' => 'some key two',
            'someKeyThree' => array(
                 'id' => 1,
                 'string' => 'some key three',
            ,
       ),
   ),
   'someOtherKey' => array(

   ),
);

What I would like to do is out every array as a nested div p structure,

<div>
    <p>someKey</p> // key of first array value
    <div>
          <p>someKey2</p>
          <div>
                 <p>SomeKeyThree</p>
          </div>
    </div>
</div>

I have tried using new RecursiveIteratorIterator(new RecursiveArrayIterator($this->getData(), RecursiveIteratorIterator::CHILD_FIRST));

and using that but I am having trouble as the end tag for div never ends up right. Also once the iterator reaches the bottom of an array with no array to go into I want it to stop iterating completely.

THanks

4
  • Your wanted HTML structure is invalid. Commented Mar 17, 2013 at 14:38
  • Well make it divs instead then with p, ill change it Commented Mar 17, 2013 at 14:40
  • Do you want to generate nested UL element with every array element in your array? Commented Mar 17, 2013 at 14:40
  • Yes if possible, the documentation for arrayIterator is not the best I am having trouble with. I would also like the iteration to stop if no array is found within that iteration, thank you. Commented Mar 17, 2013 at 14:43

1 Answer 1

1

You have to call a function recursively.

function printUl($arr){
$output = "<ul>";
foreach ($arr as $key => $val){
  if (is_array($val)){
    $output .= printUl($val);
    continue;
  }
  else{
  $output .= "<li>".$val."</li>"

  }
$output .= "</ul>";
return $output;
}
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't line 4 and 5 read if (is_array($val)){ $output .= printUl($val); ... ?? i.e. $val not $key ($key will always be a scalar)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.