0

I have a big chunk of data in this format:

 [
    {"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"}
 ]

Is there any faster and more efficient way to organize and save it the database for future reference? Like making a comparison of the temperature for different days etc. [date,weather,Temp] are supposed to be in one set.

I've tried str_replace() but I'd like to know if there's any better way.

1 Answer 1

1

Taking into account your comment, it seems that is an array of objects in which every three objects make a record (that is form of: date, weather & temp) so you can create this setup with the help of collections:

$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);
               });

This will give you this output:

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: To get the array version of this collections just attach ->all() at the end.


You can check in the Collections documentation a good explanation of the chunk() and mapSpread() methods as well of the rest of the available methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Too bad the string is as I mentioned above, with square brackets only at the beginning and at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.