You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何从关联数组向目标数组推入自定义键值对

问题描述

现有一段PHP循环代码,需要对数组推入的内容做自定义键值处理:

$dataPoints1 = array();
$dataPoints2 = array();

$sql = "SELECT DATE_FORMAT(date,'%M') as 'date', income, expense FROM `balance` group by DATE_FORMAT(date,'%m');";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
          array_push($dataPoints1, $row);  **需求一:从$row向$dataPoints1数组推入自定义键值**
          array_push($dataPoints2, $row);  **需求二:从$row向$dataPoints2数组推入自定义键值**
    }
}

数据表结构及数据如下:

iddateincomeexpense
12022-05-01 00:00:002010
22022-06-01 00:00:004030
32022-07-01 00:00:006050

具体需求

  • 需求一:从关联数组$row提取指定列,生成格式为{"label":"date","y":"income"}的键值对推入$dataPoints1,最终期望输出:
[{"label":"May","y":"20"},{"label":"June","y":"40"},{"label":"July","y":"60"}]
  • 需求二:从关联数组$row提取指定列,生成格式为{"label":"date","y":"expense"}的键值对推入$dataPoints2,最终期望输出:
[{"label":"May","y":"10"},{"label":"June","y":"30"},{"label":"July","y":"50"}]

最终将通过json_encode输出这两个数组:

echo json_encode($dataPoints1);
echo json_encode($dataPoints2);

请问如何实现上述需求?

解决方案

只需要在循环内部手动构造符合要求的自定义键值数组,再推入目标数组即可,修改后的代码如下:

$dataPoints1 = array();
$dataPoints2 = array();

$sql = "SELECT DATE_FORMAT(date,'%M') as 'date', income, expense FROM `balance` group by DATE_FORMAT(date,'%m');";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
          // 处理需求一:构造label为date值,y为income值的数组
          array_push($dataPoints1, [
              'label' => $row['date'],
              'y' => $row['income']
          ]);
          // 处理需求二:构造label为date值,y为expense值的数组
          array_push($dataPoints2, [
              'label' => $row['date'],
              'y' => $row['expense']
          ]);
    }
}

// 输出JSON
echo json_encode($dataPoints1);
echo json_encode($dataPoints2);

代码说明

  • 循环中每次取出$row后,不再直接推入原数组,而是创建新的关联数组,指定label和y两个键,分别对应$row中的date字段和目标金额字段(income/expense)。
  • 这样处理后,$dataPoints1和$dataPoints2就会完全符合期望的结构,最后通过json_encode就能输出目标JSON格式。

内容的提问来源于stack exchange,提问作者Kyaw Wint Thu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:35:18