Create JSON object using PHP

前端 未结 5 644
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 00:40

How can I achieve or create this type JSON object using PHP?

{ 
    \"label\": \"Devices per year\",
    \"data\": [
        [1999, 3.0], [2000, 3.9], [200         


        
相关标签:
5条回答
  • 2020-12-05 01:09

    I prefer the following syntax which gets the desired result and is clear to read:

    $ar = array(
                "label" => "Devices per years",
                "data" => array(array(1999, 3.0), array(2000, 3.9) )
            );
    
    var_dump(json_encode($ar));
    

    The only difference being that in the output "3.0" is rendered as "3". If you need the trailing ".0" you could surround those values with quotes.

    0 讨论(0)
  • 2020-12-05 01:11
    $obj = new stdClass();
    $obj->label="Devices per year";
    $obj->data = array(
        array('1999','3.0'),
        array('2000','3.9'),
        //and so on...
    );
    
    echo json_encode($obj);
    
    0 讨论(0)
  • 2020-12-05 01:12

    Try using this

    $arrayDateAndMachine = array(   array("1999","3.0"), 
                                    array("2000","3.9")
                                    );
    
    0 讨论(0)
  • 2020-12-05 01:14

    square brackets [] in json is array so you have to do it like this

    <?php
    
    $arrayDateAndMachine = array( 
        array(1999, 3.0), 
        array(2000, 3.9),
    );
    
    $arr = array("label" => "Devices per year", 
                 "data" => $arrayDateAndMachine);
    
    var_dump(json_encode($arr));
    
    0 讨论(0)
  • 2020-12-05 01:25

    Doing something like this should work if you would like to declare it as JSON only and not by using json_encode. This also eliminates the need to declare multiple variables for each of the arrays inside. But this would be a viable solution only if the contents of the array for data is finite.

    $json_string = '{ 
    "label": "Devices per year",
    "data": [
        [1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]
    ]}';
    
    0 讨论(0)
提交回复
热议问题