How to json_encode php array but the keys without quotes

后端 未结 5 1379
半阙折子戏
半阙折子戏 2020-12-06 04:52

I\'m trying to plot (with Flot) a pie chart with some data

var data = 

The result I get from that is t

5条回答
  •  星月不相逢
    2020-12-06 05:06

    First, you have to generate your array in php so the data's value are integers, not strings:

    I emulated your array from your json_encode(), I guess it looks like this (or it should):

    $array =  array(
                    array("label" => "Crear Usuario",   "data" => 2),
                    array("label" => "Impresoras",      "data" => 1),
                    array("label" => "Problema Correo", "data" => 1),
                    array("label" => "Requisicion Equipo", "data" => 1),
                    array("label" => "Sitio Web", "data" => 1)
                );
    
        $data = json_encode($array);
    
    • Notice that the 2 and 1's are unquoted, so this way they are integers, this is important.

    Then you are missin in Javascript the JSON.parse() to actually make that output into a json object:

    
    
    • Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

    The console.log()'s output this for me:

    [Object, Object, Object, Object, Object] // First console.log(): one object with the 5 Objects. 
    Object {label: "Crear Usuario", data: 2} // secons console log (json[0]) with the first object 
    

    Looks like what you need, am I right?

提交回复
热议问题