php - 转换为数组或集合或列表
问题描述
我有大量这种格式的数据:
[
{"date":"2018-11-17"},{"weather":"sunny"},{"Temp":"9"},
{"date":"2014-12-19"},{"Temp":"10"},{"weather":"rainy"},
{"date":"2018-04-10"},{"weather":"cloudy"},{"Temp":"15"},
{"date":"2017-01-28"},{"weather":"sunny"},{"Temp":"12"}
]
有没有更快更有效的方法来组织和保存数据库以供将来参考?像比较不同日子的温度等[date,weather,Temp]
应该是一组。
我试过str_replace()
了,但我想知道是否有更好的方法。
解决方案
考虑到您的评论,这似乎是一个对象数组,其中每三个对象创建一个记录(即形式:date
,weather
& temp
),因此您可以在集合的帮助下创建此设置:
$string = ['your', 'json', 'string'];
$records = collect(json_decode($string))
->chunk(3) // this creates a subset of every three items
->mapSpread(function ($date, $weather, $temp) { // this will map them
return array_merge((array) $date, (array) $weather, (array) $temp);
});
这将为您提供以下输出:
dd($records);
=> Illuminate\Support\Collection {#3465 all: [ [ "date" => "2018-11-17", "weather" => "sunny", "Temp" => "9", ], [ "date" => "2014-12-19", "Temp" => "10", "weather" => "rainy", ], [ "date" => "2018-04-10", "weather" => "cloudy", "Temp" => "15", ], [ "date" => "2017-01-28", "weather" => "sunny", "Temp" => "12", ], ], }
PS:要获得这个集合的数组版本,只需->all()
在最后附上。
您可以在Collections文档中查看对chunk()
和mapSpread()
方法以及其他可用方法的很好解释。
推荐阅读
- git - Git:找出你分叉的仓库的 URL 或名称
- swift - 在 ARKit / RealityKit 中同时使用水平面和垂直面
- pdf - 可填写的 pdf 不适用于不同的设备
- c# - .Slerp 的第三个参数
- python-3.x - 在 pydroid 上安装 Shapely 和 GDAL 的错误
- apache-spark - emrfs 同步和导入卡住并且无法正常工作
- bash - 在 bash 脚本中读取从 psql 返回的错误
- c++ - 当实现完全在我的 .HPP 文件中时,编译器正在寻找 .CPP 文件
- javascript - 使 HTML 元素继承另一个元素的变换
- android - 如何在 Kotlin 的 Fragment 中获取非 null 和 runOnUIThread() 的活动?