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?

Recommended Answers

All 8 Replies

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?

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)  }  }
Member Avatar for diafol
$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);    

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

Member Avatar for diafol

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(...)

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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.