Skip to content
Advertisement

building a function that will generate this json [closed]

I am working on building a JSON for a morris graph and I am having a couple of problems.

this is the format I need to get:

[
  { y: '15:44', a: 123123},
  { y: '15:29', a: 4859},
  { y: '15:14', a: 3830 },
  { y: '14:58', a: 2815 },
  { y: '14:43', a: 1810},
  { y: '14:28', a: 801 },

]

I get these two values looping threw a single array and in every cycle, I can reed both of them.

I am adding this to tell anyone who can find this helpful that the best solution I could find is this:

while($row = mysqli_fetch_array($result))
{
    $chart_data .= "{ dt:'".$row["dt"]."', totali:".$row["totali"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);

this $chart_data than can be used as a feeding variable for the chart right away

Advertisement

Answer

$arr = []
$obj = new stdClass();
$obj->y = '15:44';
$obj->a = 123123;
$arr[] = $obj;

$encoded_obj = json_encode($arr);

Just loop through your items and create an empty object. After creating the empty object assign the values to an array and with json_encode make the array a json string

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement