我需要从 php 数组生成以下类型的输入:
dataLayer = [{
key: 'value',
key2: {
key3: ['value2','value3','value4'],
key4: ['value5','value6']
}
}];
我编写了以下函数来完成它,但它并不优雅而且可能很复杂。它是否存在类似的东西但在 PHP 中构建?它类似于json_encode()
函数,但有一些区别:
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 );