The basic issue here is that you don't know how many elements $elm
will contain. foreach
is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach
loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][]
is the important bit here. On each iteration of the outer loop, the value of $elem
will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a']
, $arr['b']
and $arr['c']
and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";