story ks
story ks

Reputation: 850

Laravel Collection. Combine same key

I want to combine same keys in Laravel collection, that are stored in an array.

I can't "invent" a proper neat and short pipeline for such a transformation.

Data array

enter image description here

Example Result

enter image description here

Upvotes: 1

Views: 2085

Answers (2)

water_ak47
water_ak47

Reputation: 1306

$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

Upvotes: 0

doubleui
doubleui

Reputation: 556

It looks like you have two equal arrays inside and you need concat [0] and [1] keys to week days (from - to). Here is the solution for your collection-as-array:

<?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);

Result is:

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"
}
}

Upvotes: 4

Related Questions