4

I have a dataset that needs to be in the same format as a JavaScript variable like below:

var theData = {
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(179,181,198,0.2)",
            borderColor: "rgba(179,181,198,1)",
            data: [65, 59, 90, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            data: [28, 48, 40, 19, 96, 27, 100]
        }
    ],
    labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"]
};

The data is being built in PHP but I can't get it quite like that.

Here is what I have in PHP (sample data, but same method of filling it):

$data = array();

$data['datasets'][1]['label']           = "First Data Set";
$data['datasets'][1]['borderColor']     = "rgba(30, 87, 153, .9)";
$data['datasets'][1]['backgroundColor'] = "rgba(30, 87, 153, .5)";

$data['datasets'][2]['label']           = "Afternoon";
$data['datasets'][2]['borderColor']     = "rgba(41, 137, 216, .9)";
$data['datasets'][2]['backgroundColor'] = "rgba(41, 137, 216, .5)";

// Loop through some foreachs and fill the $data
// Not the actual loop I use but same principle

foreach ($theData as $data)
{
    $data['datasets'][1]['data'][] = data;
}

foreach ($otherData as $data)
{
    $data['datasets'][2]['data'][] = data;
}

This is returned back to JavaScript using a json_encode(); when I do console.log(JSON.stringify(theData)) I get this:

{
    "datasets":{
        "1":{
            "label":"Morning",
            "borderColor":"rgba(125, 185, 232, .9)",
            "backgroundColor":"rgba(125, 185, 232, .5)",
            "borderWidth":1,
            "data":[
                "24",
                0,
                0,
                "30",
                "24",
                "36",
                "36"
            ]
        },
        "2":{
            "label":"Afternoon",
            "borderColor":"rgba(41, 137, 216, .9)",
            "backgroundColor":"rgba(41, 137, 216, .5)",
            "borderWidth":1,
            "data":[
                "24",
                0,
                0,
                "24",
                "24",
                "30",
                "36"
            ]
        }
    },
    "labels":[
        "Sun Aug 14",
        "Mon Aug 15",
        "Tue Aug 16",
        "Wed Aug 17",
        "Thu Aug 18",
        "Fri Aug 19",
        "Sat Aug 20"
    ]
}

This is for Chart.js 2.3. The sample data up top is directly from Chart.js sample data. The JSON above is my results. Because they are not identical, the chart is not working. I can I change my PHP to make it more like the sample at the very top?

5
  • 3
    Why did you not use json_encode($data) in your PHP Commented Oct 18, 2016 at 16:16
  • 1
    @KickingLettuce It would help if you created an array the normal way. $data['datasets'] = array(); $data['datasets'][] = array('label' => 'First Data Set', ... Commented Oct 18, 2016 at 16:22
  • Please do. That is the only way you can ensure that data received is in proper JSON format. Commented Oct 18, 2016 at 16:30
  • @Rishabh Sorry, I misread something. I am using it. Sorry for going back and forth on that one. Commented Oct 18, 2016 at 16:30
  • The answer @Machavity is correct Commented Oct 18, 2016 at 16:31

1 Answer 1

6

Let's start from the top

  • theData is an object
  • datasets is an array of objects
  • labels is an array

So let's set about building this

$data = array();
$data['datasets'] = array();
$data['datasets'][] = array("label" => "First Data Set",
     "borderColor" => "rgba(30, 87, 153, .9)",
     "backgroundColor" => "rgba(30, 87, 153, .5)"
     );
$data['datasets'][] = array("label" => "Second Data Set",
     "borderColor" => "rgba(41, 137, 216, .9)",
     "backgroundColor" => "rgba(41, 137, 216, .9)"
     );

$data['labels'] = array("Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running");

echo json_encode($data);

As mentioned, json_encode does all the work for you here once you build the array

{
  "datasets": [
    {
      "label": "First Data Set",
      "borderColor": "rgba(30, 87, 153, .9)",
      "backgroundColor": "rgba(30, 87, 153, .5)"
    },
    {
      "label": "Second Data Set",
      "borderColor": "rgba(41, 137, 216, .9)",
      "backgroundColor": "rgba(41, 137, 216, .9)"
    }
  ],
  "labels": [
    "Eating",
    "Drinking",
    "Sleeping",
    "Designing",
    "Coding",
    "Cycling",
    "Running"
  ]
}
Sign up to request clarification or add additional context in comments.

4 Comments

yeah, its work, I had not seen so array in array, thanks for the clarification
This looks like a good way of doing it, let me test. Thanks.
I dont understand why if I set my keys like` $data['datasets'][1], instead of $data['datasets'][] instead it changes it from an Array of Objects to an Object of Objects (at least based on the way JSON.stringify(theData) prints out.)
@KickingLettuce It's because of how JSON has to work. Let's say you set key 1 but not key 0. json_encode will preserve that 1 key by converting it to a JSON object. Remember, JS has no actual associative arrays like PHP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.