As some of you might know I like to offer help to fellow Softwerkers around the world from time to time. I see that as a great opportunity to combine and enjoy several positive aspects: offering help and experience, community building, an opportunity to peek over the own horizon by getting to know others, a geeky hobby and last but not least simply practicing my coding skills…

Today I came upon a question about the creation of nested structures, one of the great riddles that probably only geeks experience as “interesting”. Although I doubt that the desired data architecture chosen by the original questioner is a good one I accepted the challenge and implemented a small demonstration of a reference based approach to building such a structure. That is an approach I have used in a recurring manner over the last years,: it allows to build complex nested structures in a very compact implementation and keeps the memory footprint of the final algorithm relatively small.

Here is the link to my Answer on StackOverflow.

Note, that the actual code to build that nested structure consists of only a mere 12 clever lines:

$catalog = [];
$structure = [];
foreach ($table as $key=>&$entry) {
$entry[‘pos_over’] = [];
if ($entry[‘pos_under’] == 0) {
$structure[] = &$entry;
$catalog[$entry[‘PID’]] = &$structure[count($structure)-1];
} else {
$catalog[$entry[‘pos_under’]][‘pos_over’][] = &$entry;
$catalog[$entry[‘PID’]] = &$catalog[$entry[‘pos_under’]][‘pos_over’][count($catalog[$entry[‘pos_under’]][‘pos_over’])-1];

What I try to express here is that in my opinion PHP is a flexible but well proven language that offers much more than what is often used or expected from it. Statements like “references don’t really work in PHP” or general things like “PHP is not an elegant language” which I have heard so many times are simply not justified. Tools are always only as good as the one using them…