1

I want to change array formatting in php but i'm getting error.

I want output like this

[
  ['Year', 'Sales', 'Expenses', 'Profit'],
  ['2014', 1000, 400, 200],
  ['2015', 1170, 460, 250],
  ['2016', 660, 1120, 300],
  ['2017', 1030, 540, 350]
]

php code

$sql = mysql_query("SELECT `year`, `sales`,`expenses`,`profit` 
              FROM chart 
              ORDER BY `year` ASC");

$data = array('Year','Sales','Expenses','Profit');

while ($row = mysql_fetch_array($sql)) {
   $data[] = array($row['year'], $row['sales'], $row['expenses'], 
   $row['profit']);
}

echo json_encode($data);

Output

["Year","Sales","Expenses","Profit",
["2012","20000","15000","5000"],
["2013","30000","18000","12000"],
["2014","100000","60000","40000"],
["2015","250000","150000","100000"],
["2016","15000","12000","3000"]
]
3
  • 3
    $data = array(array('Year','Sales','Expenses','Profit')); Commented Dec 6, 2017 at 9:05
  • mysql_ functions are deprecated! Commented Dec 6, 2017 at 9:05
  • This is a typo question, you know how to push rows with []. You will want echo json_encode(array_merge([['Year', 'Sales', 'Expenses', 'Profit']], mysqli_fetch_all($resultObj, MYSQLI_NUM))); when you replace mysql_ with mysqli_. Commented Sep 12, 2024 at 1:19

1 Answer 1

2

Change

$data = array('Year','Sales','Expenses','Profit');

To

$data[] = array('Year','Sales','Expenses','Profit');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.