How can I combine data from multiple arrays into one associated array and group them by a specific property?

  laravel, php

I have an application which allows users to book holidays/absences off from work. It has a feature which allows people to print a PDF of all the user holidays. I need to create another feature which allows users to print a PDF which shows each department, the users in that department, number of holidays/absences they have requested and how many holidays they have left.

I have 3 arrays which look like this:

Users total holidays:

array:1 [▼
      0 => {#1330 ▼
        +"name": "joshr"
        +"department": "Director"
        +"total_holidays": 20.0
      }
      1 => {#1324 ▼
        +"name": "perrysm"
        +"department": "Marketing"
        +"total_holidays": 18.5
      }
      2 => {#1328 ▼
        +"name": "sarahl"
        +"department": "Sales"
        +"total_holidays": 16.0
      }
      3 => {#1332 ▼
        +"name": "jamiep"
        +"department": "Sales"
        +"total_holidays": 21.0
      }
    ]

Holidays Count:

array:2 [▼
  0 => {#215 ▼
    +"user_name": "joshr"
    +"user_department": "Director"
    +"holidays_count": 2
  }
  1 => {#1307 ▼
    +"user_name": "perrysm"
    +"user_department": "Marketing"
    +"holidays_count": 4
  }
  2 => {#1328 ▼
    +"user_name": "sarahl"
    +"user_department": "Sales"
    +"holidays_count": 8
  }
  3 => {#1332 ▼
    +"user_name": "jamiep"
    +"user_department": "Sales"
    +"holidays_count": 0
  }
]

Absences Count:

array:3 [▼
  0 => {#1388 ▼
    +"user_name": "joshr"
    +"user_department": "Director"
    +"absences_count": 1
  }
  1 => {#1389 ▼
    +"user_name": "perrysm"
    +"user_department": "Marketing"
    +"absences_count": 2
  }
  2 => {#1328 ▼
    +"user_name": "sarahl"
    +"user_department": "Sales"
    +"absences_count": 4
  }
  3 => {#1332 ▼
    +"user_name": "jamiep"
    +"user_department": "Sales"
    +"absences_count": 2
  }
]

I would like to merge all 3 arrays with the output being something like the following:

array:0 [▼
  'Director' => {#215 ▼
    +"user_name": "joshr"
    +"holidays_count": 2
    +"absences_count": 1
    +"total_holidays": 20.0
  }
  'Marketing' => {#1307 ▼
    +"user_name": "perrysm"
    +"holidays_count": 4
    +"absences_count": 2
    +"total_holidays": 18.5
  }
  'Sales' => {#1307 ▼
    +"user_name": "sarah"
    +"holidays_count": 4
    +"absences_count": 8
    +"total_holidays": 16.0
  }
             {#1332 ▼
    +"user_name": "jamiep"
    +"holidays_count": 0
    +"absences_count": 1
    +"total_holidays": 21.0
  }
]

I can then display this array in a table for the UI.

Source: Laravel

Leave a Reply