dongxie2613
dongxie2613
2014-09-28 11:00

尝试为NVD3图表创建JSON代码

已采纳

I'm absolutely stuck with this piece of code, I've searched and searched to get it working and have failed miserably.

My Json output currently looks like this

 [
    {
        "key": "OWM1",
        "values": [
            [
                "x : EW",
                "y :4"
            ],
            [
                "x : RSE",
                "y :3"
            ],
            [
                "x : SWE",
                "y :2"
            ],
            [
                "x : WTE",
                "y :1"
            ],
            [
                "x : WWE",
                "y :1"
            ]
        ]
    },
    {
        "key": "OWM2",
        "values": [
            [
                "x : EW",
                "y :4"
            ],
            [
                "x : RSE",
                "y :2"
            ],
            [
                "x : SWE",
                "y :1"
            ],
            [
                "x : WTE",
                "y :3"
            ],
            [
                "x : WWE",
                "y :2"
            ]
        ]
    }
]

But I need it to look like this for the sake of NVD3 chart to be able to process it correctly.

[
  {
    "key": "OWM1",

    "values":
      [      
        { x : "EW", y : 4 },
        { x : "RSE", y : 3 },
        { x : "SWE",   y : 2 }  
        { x : "WTE",   y : 1 }  
        { x : "WWE",   y : 21 }  
      ]
  },
   {
    key: "OWM2",

    values:
      [      
        { x : "EW", y : 4 },
        { x : "RSE", y : 2 },
        { x : "SWE",   y : 1 }  
        { x : "WTE",   y : 3 }  
        { x : "WWE",   y : 2 } 
      ]
  }]

Here is my PHP code that I am producing the first output of json with.

$result = mysqli_query($con,"SELECT CODE, _POS, COUNT(CODE) AS COUNT from defects WHERE FPOS IN ('OWM1','OWM2') GROUP BY POS, CODE");


if($result) {
    $jsonData = convert($result);
}

function convert($result) {

    $intermediate = array();

    while($rows = mysqli_fetch_assoc($result)) {
        $key = $rows['POS'];
        $x = $rows['CODE'];
        $y = $rows[''];
        $intermediate[$key][] = array('x : ' .$x,'y :' . $y);
    }


   $output = array();

    foreach($intermediate as $key => $values) {
        $output[] = array(
            "key" => $key,
            'values' => $values
        );
    }

    echo json_encode($output);

}





mysqli_close($con);

Is there any way anyone could help me manipulate the code I have to look exactly like the second set of JSON code that is compatible with NVD3 charts?

Thanks alot.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongningce9075 dongningce9075 7年前

    It looks like you are creating a non-associative array here...

    $intermediate[$key][] = array('x : ' .$x,'y :' . $y);
    

    Replace that with...

    $intermediate[$key][] = array('x' => $x, 'y' => $y);
    
    点赞 评论 复制链接分享

相关推荐