1

I'm creating simple PHP for output data to apexcharts javascript charts. To make apexcharts usable output I need to provide x and y value of the graphs as JSON. below code, I wrote to output the expected JSON.

$data_arr = array();

    global $mysqli_conn;
    $result = $mysqli_conn->query("sql");
    $sql_out = array();
    $sql_out = $result->fetch_all(MYSQLI_ASSOC);
    $num_rows = mysqli_num_rows($result);

        if ($num_rows < 1){
            echo "zero";
        }else{
            foreach($sql_out as $item) {
                $data_arr['x'][] = $item['time'];
                $data_arr['y'][] = $item['status_code'];
            }
        }



$test_arr = array(
    array(
        "name"=>"lock",
        "data"=>array($data_arr),
    )
);

echo json_encode($test_arr);

my expected json output is like below

[
    {
        "name": "lock",
        "data": [
                    {
                        "x": "2019-05-30 07:53:07",
                        "y": "1470"
                    },
                    {
                        "x": "2019-05-29 07:52:27",
                        "y": "1932"
                    }
                ]
    }
]

But when I request data from my code what I'm getting something like this

[
    {
        "name": "lock",
        "data": [
            {
                "x": [
                    "2019-05-30 07:53:07",
                    "2019-05-29 07:52:27",
                    "2019-05-26 15:46:56",
                    "2019-05-25 07:39:24"
                ],
                "y": [
                    "1470",
                    "1932",
                    "1940",
                    "1470"
                ]
            }
        ]
    }
]

How can I create my expected JSON result from PHP code?.

1 Answer 1

1

You're creating them on a seprate space. When you declare and push them, put them on one container:

foreach ($sql_out as $item) {
    $data_arr[] = array(
        'x' => $item['time'],
        'y' => $item['status_code']
    );
}

When you do this:

$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];

They are on a separate containers, x and y containers, therefore you get the wrong format, like the one you showed.

When you declare them as:

$data_arr[] = array(
    'x' => $item['time'],
    'y' => $item['status_code']
);

You're basically tellin to push the whole sub batches but together.

Sign up to request clarification or add additional context in comments.

Comments

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.