phparrayslaravelphp-7

Filtering, flattening and renaming keys in multidimensional array (Mayflower/Holidays)


I am using Mayflower/Holidays in Laravel 7 to get a list of holidays for my region. What I am getting as Json is:

{"2":{"type":"holiday","name":"My Holiday 1","weight":1,"date":"2020-05-01 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"5":{"type":"holiday","name":"My Holiday 2","weight":1,"date":"2020-05-20 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"}}

That's correct but I need a different representation.

[{"title":"My Holiday 1","start":"01.05.2020"},{"title":"My Holiday 2","start":"20.05.2020"}]

Much lighter, one-dimensional and the keys name and date are supposed to be renamed to title and start. I tried various approaches using foreach with array_map but getting errors constantly. What is the best way to do this with PHP 7?


Solution

  • Since you have tagged Laravel as well, I can show you Laravel Collection each() method.

    // your input
    $jsonHolidays = '{"2":{"type":"holiday","name":"My Holiday 1","weight":1,"date":"2020-05-01 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"5":{"type":"holiday","name":"My Holiday 2","weight":1,"date":"2020-05-20 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"}}';
    
    // convert json into array
    $arrayHolidays = json_decode($jsonHolidays, true);
    
    // Using laravel collection
    $holidays = [];
    collect($arrayHolidays)->each(function ($holiday) use (&$holidays) {
        $holidays[] = [
            'title' => $holiday['name'],
            'start' => \Carbon\Carbon::parse($holiday['date'])->format('d.m.Y')
        ];
    });
    
    // converting back to json
    return json_encode($holidays, true);