我想将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 )
)
1条答案
按热度按时间46scxncf1#
使用
array_keys()
和array_values()
并不是一个理想的/最佳的方法,因为这会在访问数据时产生不必要的深度。看看每次调用后[0]
是如何被写入的吧?如果你只想访问其中的第一项,那么创建一个临时数组并不是最好的做法。只需要使用key()
和current()
(或者reset()
)。使用
array_map()
进行函数式编程:(Demo)(英文)经典foreach():(Demo)
或者使用较少的迭代函数调用:(Demo)
或者与
compact()
:(Demo)