LaravelCollection。合并相同的密钥

Laravel Collection. Combine same key

我想组合 Laravel collection 中存储在数组中的相同键。

我无法 "invent" 用于此类转换的适当简洁的管道。

数据数组

示例结果

看起来您内部有两个相等的数组,您需要将 [0] 和 [1] 键连接到工作日(从 - 到)。这是您的集合数组的解决方案:

<?php

$youHaveArray = [
    0 => [
        'mon' => [
            3 => '10:00',
            4 => '11:00',
            5 => '12:00',
        ],
        'tue' => [
            3 => '11:00',
            4 => '12:00',
        ],
    ],
    1 => [
        'mon' => [
            3 => '10:30',
            4 => '11:30',
            5 => '12:30',
        ],
        'tue' => [
            3 => '11:30',
            4 => '12:30',
        ],
    ]
];

$daysOfWeekYouHave = array_keys($youHaveArray[0]) + array_keys($youHaveArray[1]);
$weekFormated = [];

foreach ($daysOfWeekYouHave as $dayName) {

    if (! isset($weekFormated[$dayName])) {
        $weekFormated[$dayName] = [];
    }

    if (isset($youHaveArray[0][$dayName])) {
        foreach ($youHaveArray[0][$dayName] as $dayKey => $dayStart) {
            if (isset($youHaveArray[1][$dayName][$dayKey])) {
                $dayEnd = $youHaveArray[1][$dayName][$dayKey];
                $weekFormated[$dayName][$dayKey] = $dayStart.' - '.$dayEnd;
            }
        }
    }
}

var_dump($weekFormated);

结果是:

array(2) {
'mon' =>
array(3) {
    [3] =>
    string(13) "10:00 - 10:30"
    [4] =>
    string(13) "11:00 - 11:30"
    [5] =>
    string(13) "12:00 - 12:30"
}
'tue' =>
array(2) {
    [3] =>
    string(13) "11:00 - 11:30"
    [4] =>
    string(13) "12:00 - 12:30"
}
}
$result = array();

//$data is array which contains the stdClass

foreach ($data as $key => $value) {

 $name = $value->video_id;

 if (!isset($result[$name])) {
  $result[$name] = [];
 }

 $result[$name]['video_id'] = $value->video_id;
 $result[$name]['video_name'] = $value->video_name;
 $result[$name]['category_type'][] = [
  'category_id' => $value->category_id,
  'category_name' => $value->category_name,
 ];
}