I have an indexed array of associative arrays like so:
array
0 =>
array
'topic' => 'Topic 1'
'question' => 'Topic 1, Question 1'
'answer' => no'
1 =>
array
'topic' => 'Topic 2'
'question' => 'Topic 2, Question 1'
'answer' => 'yes'
2 =>
array
'topic' => 'Topic 2'
'question' => 'Topic 2, Question 2'
'answer' => 'yes'
3 =>
array
'topic' => 'Topic 3'
'question' => 'Topic 3, Question 1'
'answer' => 'yes'
and I would like to output markup that 1) Creates a header for each unique section based on the topic key; and 2) Wraps each discrete section in a <section>
element like so:
<section>
<header>Topic 1</header>
<p>Topic 1, Question 1</p>
</section>
<section>
<header>Topic 2</header>
<p>Topic 2, Question 1</p>
<p>Topic 2, Question 2</p>
</section>
<section>
<header>Topic 3</header>
<p>Topic 3, Question 1</p>
</section>
I've been able to set up a foreach
loop that correctly generates the headers for each topic, but I'm having trouble adding the opening/closing <section>
elements as needed. I'm currently using array_key_first
and array_key_last
to add <section>
elements around the entire set, but how can I adjust this loop to add open/close section elements for each topic group?
$topic = null;
foreach ( $array as $key => $item ) {
if ( $key === array_key_first($array) ) {
$html .= '<section>';
}
if ( $item['topic'] != $topic ) {
$topic = $item['topic'];
$html .= '<header>' . $topic . '</header>';
}
$html .= '<p>Question: ' . $item['question'] . '</p>';
$html .= '<p>Answer: ' . $item['answer'] . '</p>';
if ( $key === array_key_last($array) ) {
$html .= '</section>';
}
}