【问题标题】:Return values of sql into a JSON array将 sql 的值返回到 JSON 数组中
【发布时间】:2018-01-27 01:31:57
【问题描述】:

我有一个 SQL 查询,我使用一个 foreach 将这些值返回到一个 JSON 数组中。这是我的代码的样子:

$sql = "SELECT SUM(sales) from sales ... blah blah";
$result = mysqli_query($connection, $sql);
$output = array();

foreach(result as $row) {
    $output[] = $row;
}

$json = json_encode($output);
echo $json; // Returns the array

数组当前如下所示:

[{"SUM(sales)}"."10000"},[{"SUM(sales)}"."51221"},[{"SUM(sales)}"."2351"}]

我希望它是这样的: [10000, 51221, 2351]

当我使用decode($output) 时,它返回NULL

【问题讨论】:

  • “销售”表是否有“销售”列?
  • (*) 如果您的 sql 有用户输入(例如来自 GET 或 POST 变量),那么您需要更改为使用准备好的语句、执行和 fetch。否则你很容易受到 sql 注入攻击。
  • decode($output) 是什么意思?这不是我所知道的任何 php 函数。
  • @derloopkat 是的
  • @IncredibleHat json_decode($output),我的意思是。对不起!

标签: php arrays json mysqli


【解决方案1】:

试试这个

$result = mysqli_query($connection, $sql);
$output = array();
foreach($result as $row){
    array_push($output, $row['SUM(sales)']);
}
$json = json_encode($output);
echo $json; 

【讨论】:

  • 提供有关您的解决方案的一些信息将对 OP 和其他访问 SO 的人有更多帮助,因此请更新您的答案。
  • 当然,我明天就可以了,目前我有一个深夜
  • 还有一种使行字段选择更清晰的方法,就是在 SQL 中像这样调整它:SELECT SUM(sales) as SumSales FROM sales ... 这样你就可以使用$row['SumSales'](如果这对你来说更具可读性,我个人总是命名 SUM() 和 COUNT(*) 等)。
猜你喜欢
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多