Array to google charts
Results 1 to 8 of 8

Thread: Array to google charts

  1. #1
    Member
    Join Date
    Nov 2006
    Posts
    44

    Array to google charts

    I need to get the array to be in the right format for the chart.

    Current output array
    Code:
    Array
    (
        [May] => 1
        [Apr] => 64
        [Sep] => 3
        [Aug] => 1
        [Mar] => 66
        [Feb] => 29
    )
    My code to try and get it to this: [["month":"Incidents"],["May":1],["Apr":64],["Sep":3],["Aug":1],["Mar":66],["Feb":29]]
    PHP Code:
    // Prepare the data in the correct format
            
    $formatted_months = array();
            
    $i=0;
            
    $formatted_months[] =  "['months','Incidents']";
            foreach (
    $result as $key => $value) {
                
    $formatted_months[] =  "['"$key ."'"$value ."]";
                
    $i++;
            }
            
    print_r($formatted_months);
            echo 
    json_encode($formatted_months); 
    At the moment i get this: [{"month":"Incidents"},{"May":1},{"Apr":64},{"Sep":3},{"Aug":1},{"Mar":66},{"Feb":29}]
    Last edited by james182; 05-21-2013 at 10:23 PM.

  2. #2
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,429
    Why not just directly JSON-encode the data and create a DataTable based on the resulting JSON string?

    EDIT: Okay, so you might have to restructure the array so that it looks more like format described here, but that still seems like a more straightforward approach (IMHO).
    Last edited by bradgrafelman; 05-21-2013 at 10:58 PM.

  3. #3
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,874
    Quote Originally Posted by james182 View Post
    At the moment i get this: [{"month":"Incidents"},{"May":1},{"Apr":64},{"Sep":3},{"Aug":1},{"Mar":66},{"Feb":29}]
    I tried a slightly different approach and get the same results -- it looks like the php function json_encode by default will encode an associative array (meaning it has non-numeric keys) as an object by default rather than as an array. I find this interesting because, unless I'm mistaken, Javascript supports associative arrays. Here's what I tried:
    PHP Code:
    $months = array(
        
    "May" => 1,
        
    "Apr" => 64,
        
    "Sep" => 3,
        
    "Aug" => 1,
        
    "Mar" => 66,
        
    "Feb" => 29,
    );

    $google_array[] = array("month" => "Incidents");
    foreach(
    $months as $key => $value) {
      
    $google_array[] = array($key => $value);
    }

    echo 
    json_encode($google_array); 
    Unfortunately, while you can supply an option JSON_FORCE_OBJECT to make json_encode use objects for numerically indexed arrays, there is no option to force an array for associatively indexed arrays -- which is kind of lame, I think. On the other hand, I'm not an expert in the JSON syntax.

    I can't help but wonder if the result we both get will actually work with google chart. Have you tried it?

    If it doesn't work, you can do an str_replace on your result to change all the curly brackets to square brackets. This will work as long as none of your keys or values contain curly brackets:
    PHP Code:
    // assumes you are using my code above
    $json json_encode($google_array);
    $json str_replace("{""["$json);
    $json str_replace("}""]"$json); 
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  4. #4
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,885
    Quote Originally Posted by sneakyimp
    there is no option to force an array for associatively indexed arrays -- which is kind of lame, I think. On the other hand, I'm not an expert in the JSON syntax.
    JSON is a subset of JavaScript syntax. JavaScript does not have associatively-indexed arrays (as something distinct from obejcts), therefore neither does JSON (which can be described in about six lines).
    This:
    Code:
     [{"month":"Incidents"},{"May":1},{"Apr":64},{"Sep":3},{"Aug":1},{"Mar":66},{"Feb":29}]
    Is legitimate JSON. (In other words, the output from json_encode is ... JSON.)
    This:
    Code:
     [["month":"Incidents"],["May":1],["Apr":64],["Sep":3],["Aug":1],["Mar":66],["Feb":29]]
    Is not even legitimate JavaScript, let alone legitimate JSON.
    From glancing at some of the code examples, I think what the original poster actually wants is
    Code:
     [["month","Incidents"],["May",1],["Apr",64],["Sep",3],["Aug",1],["Mar",66],["Feb",29]]
    Which is just an array of arrays - JSON-encoded.
    Last edited by Weedpacket; 05-22-2013 at 05:20 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  5. #5
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,874
    Quote Originally Posted by Weedpacket View Post
    This:
    Code:
     [["month":"Incidents"],["May":1],["Apr":64],["Sep":3],["Aug":1],["Mar":66],["Feb":29]]
    Is not even legitimate JavaScript, let alone legitimate JSON.
    My bad. You are correct about that. I tried sending it into some Javascript and it was not able to decode it, failing with an error at the first colon:
    Code:
    SyntaxError: missing ] after element list
    http://localhost/chump.php
    Line 8
    var foo = [["month":"Incidents"],["May":1],["Apr":64],["Sep":3],["Aug":1],["Mar
    ===================^
    On the other hand, I have noticed that one can define an array object and then assign it an associative property without changing its fundamental type:
    HTML Code:
    <html>
    <head> 
    <script type="text/javascript">
    var toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
    }
    var arr = new Array(0, 1, 2);
    arr["assoc_key"] = "some value";
    console.log(toType(arr)); // outputs "array"
    
    var obj =new Object();
    obj["assoc_key"] = "some value";
    console.log(toType(obj)); // outputs "object"
    </script>
    </head>
    <body>
    </body>
    </html>
    I was under the mistaken impression that JSON might be as forgiving as abuse of Javascript object types.
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  6. #6
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,885
    Quote Originally Posted by sneakyimp
    Code:
    var obj =new Object();
    obj["assoc_key"] = "some value";
    console.log(toType(obj)); // outputs "object"
    No surprise; the middle line is exactly equivalent to
    Code:
    obj.assoc_key = "some value";
    The former syntax would be used if the name of the property to be accessed was held in another variable, or if the name of the property wasn't a legitimate identifier.
    https://developer.mozilla.org/en-US/...mber_Operators
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  7. #7
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,874
    Quote Originally Posted by Weedpacket View Post
    No surprise; the middle line is exactly equivalent to
    Code:
    obj.assoc_key = "some value";
    Well to use array-style property assignment is what led me to think that associative arrays existed -- that and the fact that this code outputs a object type of "array"
    Code:
    var arr = new Array(0, 1, 2);
    arr["assoc_key"] = "some value";
    console.log(toType(arr)); // outputs "array"
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  8. #8
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,885
    Quote Originally Posted by sneakyimp
    that and the fact that this code outputs a object type of "array"
    Well, yes; because that's what you constructed:
    Code:
    var arr = new Array(0, 1, 2);
    .
    But it's an abuse of Array, which is an object that comes with a whole bunch of additional properties for maintaining ordered lists. Try these:
    Code:
    var arr = new Date();
    arr["assoc_key"] = "some value";
    console.log(toType(arr));
    console.log(arr["assoc_key"]);
    Code:
    var arr = new Array(0,1,2);
    arr["assoc_key"] = "something";
    console.log(arr.length);
    console.log(arr);
    Code:
    var arr = new Array(0,1,2);
    console.log(arr.length);
    console.log(arr.toString());
    arr["length"] = "some value";
    arr["toString"] = "something else";
    console.log(arr.length);
    console.log(arr.toString());
    Last edited by Weedpacket; 05-23-2013 at 05:18 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •