使用json中的子数组数据创建关联数组的行

uyto3xhc  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(132)

我想将JSON响应Map到特定的数组构造。
下面是我的JSON数据的简要说明:

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

我需要帮助Map此数据以具有数组结构,就像下面的look array:

Array ( 
    [0] => Array(
        [date] => 2018-01-03
        [value] => 0.0002444
    )
[1] => Array(
        [date] => 2018-01-04
        [value] => 0.0171476
    )
)

我的PHP代码:

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

之后,数组的结构看起来像这样,这不完全是我所期望的:

Array ( 
    [0] => Array ( [2018-01-03] => 0.0002444 ) 
    [1] => Array ( [2018-01-04] => 0.0171476 )
)
46scxncf

46scxncf1#

使用array_keys()array_values()并不是一个理想的/最佳的方法,因为这会在访问数据时产生不必要的深度。看看每次调用后[0]是如何被写入的吧?如果你只想访问其中的第一项,那么创建一个临时数组并不是最好的做法。只需要使用key()current()(或者reset())。
使用array_map()进行函数式编程:(Demo)(英文)

var_export(
    array_map(
        fn($item) => ['date' => key($item), 'value' => current($item)],
        json_decode($json, true)['data']
    )
);

经典foreach():(Demo

$result = [];
foreach (json_decode($json, true)['data'] as $item) {
    $result[] = ['date' => key($item), 'value' => current($item)];
}
var_export($result);

或者使用较少的迭代函数调用:(Demo

$result = [];
foreach (json_decode($json, true)['data'] as $item) {
    $key = key($item);
    $result[] = ['date' => $key, 'value' => $item[$key]];
}
var_export($result);

或者与compact():(Demo

$result = [];
foreach (json_decode($json, true)['data'] as $item) {
    foreach ($item as $date => $value) {
        $result[] = compact(['date', 'value']);
    }
}
var_export($result);

相关问题