0

I need help parsing json data to a specific format so I can put it on a line chart. More specifically a line graph using highcharts This data comes from a query

$data['graph']=$this->mymodal->graphmodal($id);

foreach ($data['graph'] as $row)    
{
 //modify array..

} 

echo json_encode($data['graph']);

The result this produces is the following

[
 {
  Name: "Dr Pepper",
  January: 4,
  February: 5
 },
 {
  Name: "Coke",
  January: 2,
  February: 4,

 },
...
...

I would like my json format to look something like this

[
  {
     Name: 'Dr Pepper',
     data: [4,5]
   }, 
   {
   Name: 'Coke',
   data: [2,4]
   }
]

Is this possible to do and how so?

3
Contributors
8
Replies
35
Views
2 Years
Discussion Span
Last Post by Israel_2
0

We need to see the array in $row, and how you are placing this into your $data['graph'] variable. How can we show you how to manipulate an array if we don't even know what we're starting with aha?

0

The array looks something like this

array(15) { [0]=> array(15) {  ["Name"]=> string(4) "Coke" ["January"]=> int(2) ["February"]=> int(5) ["March"]=> int(4) ["April"]=> int(13)  } [1]=> array(15) { ["Name"]=> string(8) "DrPepper" ["January"]=> int(14) ["February"]=> int(10) ["March"]=> int(12) ["April"]=> int(8)  }  }

Edited by Israel_2

2
$data['graph']=$this->mymodal->graphmodal($id);
$output = [];
foreach ($data['graph'] as $row)    
{
    $name = $row['Name']; 
    unset($row['Name']);
    $output[] = ['Name'=>$name,'data'=>array_values($row)];
} 
echo json_encode($output);    
1

It looks like that should work but for some reason it is not echoing in my case. I am using php 5.2 and I believe the syntax for the array it is not the same

2

If you can upgrade. You are using a version that had its last release back in 2011. That's far too old. Just substitute right hand [...] for array(...)

0

it looks like somehow the $output[] = ['Name'=>$name,'data'=>array_values($row)]; is throwing some sort of error because my page is not requesting the function where the query is coming from. If I comment out that line it does request the function.

0

nvm my last comment, instead is somehow concatenating the name array

[
{
Name: [
"Coke"
],
data: [
2,
4,
1,
2,
2,
2,
0,
0,
0,
0,
0,
0
]
},
{
Name: [
"Coke ",
"Dr Pepper"
],
data: [
7,
13,
8,
11,
14,
9,
0,
0,
0,
0,
0,
0
]
},
{
Name: [
"Coke",
"Dr Pepper",
"Mountain Dew"
],
data: [
0,
0,
2,
1,
3,
3,
0,
0,
0,
0,
0,
0
]
},

It should be one name per set

0

sorry man nvm. I got it figure it out. Thanks for your help.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.