Ok i’ve to admin i’m not a master in recursion. This could be kinda a newbie problem.
What i’m trying to do is to compute the section number. As you can see as you go in depth the section number changes in a predictable way:
multipart/mixed
-- (part 0, sec. "1") multipart/related
-- (part 0, sec. "1.1") multipart/alternative
-- (part 0, sec. "1.1.1") text/plain
-- (part 1, sec. "1.1.2") text/html
-- (part 1, sec. "1.2") image/gif
-- (part 1, sec. "2") image/png
That is, section number is simply the part number (plus 1) followed by a dot and again by the part number (plus 1), how many times depends on nesting level.
A simple $struct to pass to parse() function is like:
object(stdClass)
public 'type' => int // if 1 it's multipart
public 'parts' => array // Inner parts
While my function is quite like this:
public function parse($struct, $depth = '')
{
if(!isset($struct->parts)) return; // Base case of recursion: no parts inside
// $struct->parts is array: index starting from 0.
for($i = 0, $j = count($struct->parts); $i < $j; $i++)
{
$part = $struct->parts[$i]; // Current part
$ptno = $i + 1; // This is the part number, will be used to build $secno
// Multipart? Go further in recursion passing the new level of nesting
if($part->type == 1) $this->parse($part, $depth .= "$partno" . ".");
// Compute the section number with the given $depth (if any)
// ACTUALLY NOT WORKING
$secno = !empty($depth) ? "$depth$ptno" : "$ptno";
// Where am i?
echo self::$TYPES[$part->type] . '/' . $part->subtype . ": $secno<br/>";
}
}
Output (wrong):
text/PLAIN: 1.1.1
text/HTML: 1.1.2
multipart/ALTERNATIVE: 1.1.1
image/GIF: 1.1.2
multipart/RELATED: 1.1
image/PNG: 1.2
This is how it should be:
text/PLAIN: 1.1.1
text/HTML: 1.1.2
multipart/ALTERNATIVE: 1.1
image/GIF: 1.2
multipart/RELATED: 1
image/PNG: 2
EDIT: copy & paste test data:
$test = (object) array(
'type' => 1, // multipart
'subtype' => 'MIXED',
'parts' => array(
(object) array(
'type' => 1, // multipart
'subtype' => 'RELATED',
'parts' => array(
(object) array(
'type' => 1, // multipart
'subtype' => 'ALTERNATIVE',
'parts' => array(
(object) array('type' => 0, 'subtype' => 'PLAIN'),
(object) array('type' => 0, 'subtype' => 'HTML'),
)
),
(object) array(
'type' => 5, // image
'subtype' => 'GIF'
)
)
),
(object) array(
'type' => 5, // image
'subtype' => 'PNG'
)
)
);
The problem is you are
.=appending$partnowhen you should just be.appending here:So fixing that in the context of your code, you get:
And you can restructure your code like this to avoid code duplication more: