修改php中的数组格式

时间:2017-12-06 09:04:18

标签: php arrays

我想在php中更改数组格式,但我收到错误。

我想要这样的输出

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

php代码

$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);

输出

["Year","Sales","Expenses","Profit",
["2012","20000","15000","5000"],
["2013","30000","18000","12000"],
["2014","100000","60000","40000"],
["2015","250000","150000","100000"],
["2016","15000","12000","3000"]
]

1 个答案:

答案 0 :(得分:2)

更改

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

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