Contact us at 419.770.1960 or info@manzwebdesigns.com
Parse php array for WordPress Timber Debug Bar

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 php 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!

Bud Manz is a strong advocate of the Open Source movement, believing that the way to making one's self the best they can be is most effectively accomplished by helping other people succeed. He enjoys arranging (and singing!) hymns, gardening, and most things geeky :)