K
K
koshelevsergey2018-08-03 20:13:59
Yii
koshelevsergey, 2018-08-03 20:13:59

How to write from one array to another array?

There was a difficulty with this solution:
There is an array of history:
PS I work with Yii2 (an array like this is obtained when requesting History::find()->all(); )

$app = [
    [
        'name' => 'Вячеслав Рябов',
        'entity' => 'Менеджер',
        'data' => [
            'Статус' => 'Ожидает',
            'Тип' => 'Документ',
        ],
        'created_at' => '2018-05-02 12:38:15',
    ],
    [
        'name' => 'Рома Винатов',
        'entity' => 'Vtytl;th',
        'data' => [
            'Тип' => 'Заявка',
            'Автор' => 'Вячеслав Рябов',
            'Приоритет' => 'Высокий',
        ],
        'created_at' => '2018-05-02 09:25:35',
    ],
    [
        'name' => 'Стас Егоров',
        'entity_name' => 'Файлы',
        'data' => [
            'Статус' => 'Готов',
        ],
        'created_at' => '2018-09-12 16:14:08',
    ],
];

It is necessary to make sure that all records are displayed by the same date 2018-05-02 .
So the array should look like this:
$result = [
    '2018-05-02' => [
        [
            'name' => 'Вячеслав Рябов',
            'entity' => 'Менеджер',
            'data' => [
                'Статус' => 'Ожидает',
                'Тип' => 'Документ',
            ],
            'created_at' => '2018-05-02 12:38:15',
        ],
        [
            'name' => 'Рома Винатов',
            'entity' => 'Vtytl;th',
            'data' => [
                'Тип' => 'Заявка',
                'Автор' => 'Вячеслав Рябов',
                'Приоритет' => 'Высокий',
            ],
            'created_at' => '2018-05-02 09:25:35',
        ],
    ],
    '2018-09-12' => [
        [
            'name' => 'Стас Егоров',
            'entity_name' => 'Файлы',
            'data' => [
                'Статус' => 'Готов',
            ],
            'created_at' => '2018-09-12 16:14:08',
        ],
    ]
];

I tried to do it through foreach but without success.
Tell me how can I do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Immortal_pony, 2018-08-03
@koshelevsergey

function groupBy(array $elements, callable $getUniqueKey) {
    $grouped = [];
    
    foreach ($elements as $element) {
        $uniqueKey = $getUniqueKey($element);
        $grouped[$uniqueKey][] = $element;
    }
    
    return $grouped;
}

$groupedByDate = groupBy($app, function($event) {
    return date("Y-m-d", strtotime($event['created_at']));
});

Example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question