views:

90

answers:

5

I had php multi dimensional array

 Array
(
    [0] => Array
        (
            [WorkHrs] => 9826
            [Focus_Date] => 2010-02-10 
        )

    [1] => Array
        (
            [WorkHrs] => 9680            
            [Focus_Date] => 2010-02-11
        )

)

and I want to convert it in Javascript to

 myArray = [['2010-02-10', 9826],['2010-02-11', 9680]];

Can you advise me how to do it?

+1  A: 

json_encode

David Dorward
hi david i try it before but the example of php.net is not two dimensional array :(
mapet
@mapet: when you tried it what was the output?
BoltClock
A: 

That's pretty much exactly what json_encode does. Input is a PHP-array (other datatypes accepted), output is what you describe.

Alexander Sagen
No, if he uses `json_encode` directly, the output will be an array of JSON objects.
Matthew Flaschen
+4  A: 
$jsArray = array();
foreach($myArray as $array) {
   $jsArray[] = array($array['Focus_Date'], (int) $array['WorkHrs']); 
}

echo json_encode($jsArray);
Jacob Relkin
+4  A: 
echo json_encode(array_map(array_values, $arr));

EDIT: To get it in the specified order:

function to_focus_work_array($arr)
{
  return array($arr['Focus_Date'], $arr['WorkHrs']);
}

echo json_encode(array_map('to_focus_work_array', $arr));
Matthew Flaschen
+1 for `array_values()`. Attempting to encode associative arrays results in JSON objects, therefore you need to remove the associative keys.
BoltClock
This won't give the values in the desired order though. :)
deceze
@deceze, My answer will. :P
Jacob Relkin
@deceze: hmmm, good point.
BoltClock
@deceze, updated.
Matthew Flaschen
A: 

have you tried the json_encode()? refer to http://php.net/manual/en/function.json-encode.php

jebberwocky