首页 > 解决方案 > 转换为数组或集合或列表

问题描述

我有大量这种格式的数据:

 [
    {"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()了,但我想知道是否有更好的方法。

标签: phparrayslaravel

解决方案


考虑到您的评论,这似乎是一个对象数组,其中每三个对象创建一个记录(即形式:dateweather& 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()方法以及其他可用方法的很好解释。


推荐阅读