PHP: Implode a Multidimensional Array

I can’t image this is a common problem, but I recently needed to implode a multidimensional array into all possible combinations for a side project. Since I may need to use this again (or maybe someone else needs something similar), I thought I would post my solution here and attempt to explain it. I also put together a live demo; you might want to check it out before reading the rest of this post.

Final Result

Here is the final result for anyone just looking for the code:

function multidimensional_implode($glue, $pieces) {
    $total = 1;
    foreach ($pieces as $piece)
        $total *= count($piece);

    $variations = array_fill(0, $total, array_fill(0, count($pieces), null));

    foreach ($pieces as $j => $piece) {
        $step = ceil((count($variations) / count($piece)) / (pow(count($piece), $j)));
        for ($i = 0; $i < count($variations); $i++) {
            $k = (floor($i / $step) % count($piece));
            $variations[$i][$j] = $pieces[$j][$k];
        }
    }

    foreach ($variations as $i => $variation)
        $variations[$i] = implode($glue, $variation);

    return $variations;
}

Now that the copy-pasters have their code, the rest of us can dive in.

Continue reading “PHP: Implode a Multidimensional Array” →