0

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 );
Zachary Craig
  • 2,192
  • 4
  • 23
  • 34
Karolína Vyskočilová
  • 1,305
  • 1
  • 18
  • 29

1 Answers1

0

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.

Karolína Vyskočilová
  • 1,305
  • 1
  • 18
  • 29
  • You probably would have had better luck if your question had included the specific thing you were trying to accomplish which I'm guessing is related to [Google Tag Manager](https://developers.google.com/tag-manager/devguide) – gview Aug 15 '17 at 11:07
  • @gview You're right. But I didn't know that GTM uses the same output, it was for a small custom integration with a clients technology. – Karolína Vyskočilová Aug 15 '17 at 15:23