Reputation: 1168
I have an array of topics
. Some of them contain parent
or child
topics. I want to echo each topic even if it is a child. I loop through the array of topics, then check if the topic value is an array. If yes, then again loop through it and assign the topic to the topicName
variable. If no, then assign the topic to the variable without looping. However, when I echo topicName
it only echoes the ones in the else statement and it doesn't echo all of the topics. Can someone explain to me why it doesn't?
<?php
$topics = [
'Opening',
'Aanwezigen',
'Opmerkingen vorige notulen',
'Ingezonden stukken' => [
'Jaarverslag 2019',
'Jaarcijfers 2019',
],
'Jaarrekening 2019' => [
'Voorstel tot vaststelling van de jaarcijfers 2019 (stempunt)',
'Vaststelling dividenduitkering (stempunt)',
'Bespreking reserverings- en dividendbeleid',
],
'Rondvraag',
'Afsluiting',
];
foreach ($topics as $topic) {
if (is_array($topic)) {
for($i = 0; $i < count($topic); $i++) {
$topicName = $topic[$i];
}
} else {
$topicName = $topic;
}
echo $topicName;
}
?>
Upvotes: 0
Views: 61
Reputation: 17805
Make it recursive for it to work for any levels deep.
function recursivelyPrintTopicNames($topics){
foreach ($topics as $topic => $child_topic) {
if (is_array($child_topic)) {
echo $topic,PHP_EOL; // print parent topic here itself
recursivelyPrintTopicNames($child_topic);
} else {
echo $child_topic,PHP_EOL;
}
}
}
recursivelyPrintTopicNames($topics);
We check if current value is an array, if yes, then the key is a parent topic. We recursively call the same function to print further child topics.
If current value isn't an array, it's just a topic with no children.
Demo: https://3v4l.org/WoSJq
Upvotes: 1
Reputation: 1140
When you pass in the foreach, you overwrite with the last element so the topicName is always the last element of the array (Jaarcijfers 2019 and Bespreking reserverings- en dividendbeleid BUT other in array where not displayed : 'Voorstel tot vaststelling van de jaarcijfers 2019 (stempunt)', 'Vaststelling dividenduitkering (stempunt)', TopicName should be an array in this case.
<?php
$topics = [
'Opening',
'Aanwezigen',
'Opmerkingen vorige notulen',
'Ingezonden stukken' => [
'Jaarverslag 2019',
'Jaarcijfers 2019',
],
'Jaarrekening 2019' => [
'Voorstel tot vaststelling van de jaarcijfers 2019 (stempunt)',
'Vaststelling dividenduitkering (stempunt)',
'Bespreking reserverings- en dividendbeleid',
],
'Rondvraag',
'Afsluiting',
];
$mineTopics = [];
foreach ($topics as $key => $topic) {
if (is_array($topic)) {
// Add key
$mineTopics[] = $key;
for($i = 0; $i < count($topic); $i++) {
$mineTopics[] = $topic[$i];
}
} else {
$mineTopics[] = $topic;
}
}
var_dump($mineTopics);
EDIT:
Capture the key in the foreach loop and add it to your final array
Upvotes: 2