how to convert an array to a string format

advertisements

i have an array in the format

array() {["2011-07-29"]=> 39 ["2011-07-30"]=> 39 ["2011-07-31"]=> 39 ["2011-08-01"]=> 40}

i need to convert it to a string format like this (the below is a var_dump result)

string(584) "[new Date(2011,07,29),39], [new Date(2011, 07, 30),39],[new Date(2011, 07, 31),39], [new Date(2011, 08, 01),40]"

had anyone faced it before , iam stuck with this now...


<?php
    $a = Array("2011-07-29" => 39, "2011-07-30"=> 39, "2011-07-31"=> 39, "2011-08-01"=> 40);
    $sa = array();
    foreach($a as $k => $v){
        $sa[] = "[new Date(".preg_replace('/-/',', ',$k)."),$v]";
    }
    $s = implode(', ',$sa);
    var_dump( $s );
?>

Edit: Improved to match better features of @Alvaro's answer (virtually identical - and answered first), but with simpler string building (I find sprintf an unnecessary layer of abstraction)

<?php
    $input = array(
        '2011-07-29' => 39,
        '2011-07-30' => 39,
        '2011-07-31' => 39,
        '2011-08-01' => 40,
    );
    $aux = array();
    foreach($input as $date => $number){
        $aux[] = "[new Date(" . str_replace('-',', ',$date) . "),$number]";
    }
    $output = implode(', ', $aux);
    var_dump($input, $output);
?>