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

PHP中如何将特定JSON数据转换为目标关联数组结构

解决JSON转指定PHP关联数组的问题

问题背景

给定以下简化版JSON响应:

{
    "code": 200,
    "unit": null,
    "data": [
        {
            "2022-11-16": 185.6159202
        },
        {
            "2022-11-17": 204.31997631
        }
    ]
}

需要将其中的data数组转换为如下结构:

Array ( 
    [0] => Array(
        [date] => 2022-11-16
        [value] => 185.6159202
    )
    [1] => Array(
        [date] => 2022-11-17
        [value] => 204.31997631
    )
)

当前使用的代码:

$decoded = json_decode($json, true);
$arr = $decoded['data'];

执行后得到的结构不符合预期:

Array ( 
    [0] => Array ( [2022-11-16] => 185.6159202 ) 
    [1] => Array ( [2022-11-17] => 204.31997631 )
)

解决方案

方法一:foreach循环遍历转换

通过遍历原始数据数组,提取每个子数组的键作为date,对应值作为value,组装成目标结构:

$decoded = json_decode($json, true);
$originalData = $decoded['data'];
$result = [];

foreach ($originalData as $item) {
    // 获取子数组的唯一键(日期)
    $date = array_key_first($item);
    // 取出对应的值
    $value = $item[$date];
    // 组装新数组
    $result[] = [
        'date' => $date,
        'value' => $value
    ];
}

print_r($result);

注:array_key_first()是PHP 7.3及以上版本可用的函数,如果你的PHP版本较低,可以替换为array_keys($item)[0]。

方法二:使用array_map简化代码

利用array_map函数对原始数据数组的每个元素进行转换,代码更简洁:

$decoded = json_decode($json, true);
$result = array_map(function($item) {
    $date = array_keys($item)[0];
    return [
        'date' => $date,
        'value' => $item[$date]
    ];
}, $decoded['data']);

print_r($result);

两种方法都能将原始的单键值对子数组,转换成包含date和value固定键的目标数组结构。

内容的提问来源于stack exchange,提问作者jakab003

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:05:32