Parse PHP Array for Twig


Parse PHP Array for Twig

I recently started maintaining the Timber Debug WordPress plugin on GitHub and today I completed an interesting feature request where the requester wanted content that describes the twig variables in a twig comment to place at the top of his templates added.

The data comes in a mixed array $data containing strings, stdObject‘s, and possibly one or more arrays.  In this case, I loop through the data, checking to see if it is an array.  When it is an array, I parse it out using the builtin  PHP function, array_keys(), in another foreach loop.  See the full code below!

echo '<code>{# expected variables:';
$dataKeyNames = array_keys( $data );
$i = 0;
foreach ( $data as $d ) {
    if( is_array($d) ) {
        $varName = $dataKeyNames[$i];
        $arrayKeynames = array_keys((array) $d[0]);
        $keynames = '';
        foreach ( $arrayKeynames as $array_keyname ) {
            $keynames .= "'" . $array_keyname . "', ";
        }
    $keynames = substr($keynames, 0, -2 );
    echo "<div style='text-indent: .25in'>{$varName}: array of the form array[0][X] where X is {$keynames}</div>";
}
$i++;}
echo '#}</code>';

Thank you for visiting this post and I look forward to your comments below!

Leave a Comment

Scroll to Top