Engl12
Engl12

Reputation: 139

trying to create JSON code for NVD3 Charts

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.

Upvotes: 0

Views: 532

Answers (1)

Mitchfizz05
Mitchfizz05

Reputation: 28

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);

Upvotes: 1

Related Questions