转换为数组或集合或列表

时间:2019-05-07 21:54:47

标签: php arrays laravel

我有很多这种格式的数据:

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

1 个答案:

答案 0 :(得分:1)

考虑到您的评论,看来这是一个对象数组,其中每个三个对象进行记录(其形式为:dateweathertemp),以便您可以在集合的帮助下创建此设置:

$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()方法以及其他available methods方法的详细说明。