phparraysdata-layers

An elegant way to generate dataLayer formatted output?


I need to generate following type of input from a php array:

dataLayer = [{
  key: 'value',
  key2: {
    key3: ['value2','value3','value4'],
    key4: ['value5','value6']
  }
}];

I wrote the following function which does it, but it's not elegant and maybe way complicated. Does it exists something like that but build within the PHP? Its something like json_encode() function, but there are some differences:

function dataLayerEncode( $array ) {
    $encoded = "dataLayer[{\n";            
    $n = 1;            
    while (list($key, $val) = each($array)) {            
        if ( ! is_array( $val ) ) {
            $encoded .= "  $key: '$val'".($n < count($array) ? ',' : '')."\n";            
        } else {
            $encoded .= "  $key: {\n";
            $nn = 1;                    
            while (list($key, $value) = each($val)) {
                if ( ! is_array( $value ) ) {
                    $encoded .= "    $key: '$value'".($nn < count($value) ? ',' : '')."\n";
                } else {
                    $value = array_map( function ($el) { return "'{$el}'"; }, $value);
                    $value = implode( ',', $value );
                    $encoded .= "    $key: [$value] \n";
                }
                $nn++;
            }
            $encoded .= "  }\n";
        }
        $n++;
    }
    $encoded .= "}];\n";
    return $encoded;
}
$array = array( 'key' => 'value', 'key2' => array('key3' => array('value2','value3','value4'),'key4' => array('value5','value6') ) );
echo dataLayerEncode( $array );

Solution

  • After a months I found a solution which is lovely one-liner:

    json_encode([$array], JSON_PRETTY_PRINT)
    

    I'm quite sad that I haven't known it before, it would save me a headache with writing own script.