Laravel集合。组合相同的键

时间:2018-09-21 02:57:43

标签: php laravel laravel-5.4 laravel-collection

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

我无法为这样的转换“发明”适当而简洁的管道。

数据数组

enter image description here

示例结果

enter image description here

2 个答案:

答案 0 :(得分:2)

似乎您内部有两个相等的数组,并且需要使用concat [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"
}
}

答案 1 :(得分:0)

$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,
 ];
}

enter image description here