简体   繁体   English

在PHP中创建mySQL查询以生成列平均值的JSON数组

[英]Create mySQL query in PHP to generate JSON array of column averages

I'm trying to create a PHP script that will echo the average value of each of my columns and array them all in a single JSON array. 我正在尝试创建一个PHP脚本,该脚本将回显每列的平均值并将它们全部排列在一个JSON数组中。

I know that this is how I can get the average for a column. 我知道这是我如何获取列的平均值的方法。

select avg(`sales`) as sales  from `mytable`

But I'm not sure how to string this together 但我不确定如何将其串在一起

select avg(`sales`) as sales  from `mytable`
select avg(`profit`) as profit  from `mytable`
select avg(`costs`) as costs  from `mytable`

To get something like this echo'd from PHP: 要从PHP获得类似的回显,请执行以下操作:

[
{
    "sales": 56812
},
{
    "profit": 2312
},
{
    "costs": 324
}
]

You're close. 你近了

select
    avg(sales) as sales,
    avg(profit) as profit,
    avg(costs) as costs
from mytable;

Note that I removed the backticks around your column and table names because they are not necessary and are just visual noise and are one other thing to make mistakes about. 请注意,我删除了您的列名和表名周围的反引号,因为它们不是必需的,只是视觉上的杂音,并且是犯错误的另一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM