1

I want to print all unique Department values from a multidimensional array as a comma-separated string, but not all rows have a Department value.

The boiled down version of my array looks like this:

$employee = [
    ["employee_id" => 1, "Department" => "Tech"],
    ["employee_id" => 2, "Department" => "Tech"],
    ["employee_id" => 3],
    ["employee_id" => 4, "Department" => "Tech"],
    ["employee_id" => 5],
    ["employee_id" => 6, "Department" => "Crm"],
    ["employee_id" => 7],
    ["employee_id" => 8, "Department" => "Crm"],
    ["employee_id" => 9, "Department" => "Crm"],
    ["employee_id" => 10],
    ["employee_id" => 11, "Department" => "Crm"],
    ["employee_id" => 12, "Department" => "Crm"]
];

I tried with:

for ($i=0; $i < count($employee); $i++) {
    print_r(array_unique($employee[$i]['Department']));
}

But I generate Warnings when I try to access a non-existent Department value.

Expected output:

Tech,Crm
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
stuart
  • 57
  • 6

2 Answers2

0
<?php

echo implode(",",array_unique(array_column($employee,'Department')));

Use array_column to filter values of Department column and use array_unique() to have unique values of Department. Now, just implode() them based on ,.

nice_dev
  • 17,053
  • 2
  • 21
  • 35
0

You can avoid calling array_unique() after array_column() by repeating its second parameter as its third parameter. PHP does no allow duplicate kays on the same level as an array. When a repeated Department is encountered, the old value is replaced with its newer, identical value.

Code: (Demo)

echo implode(',', array_column($employee, 'Department', 'Department'));
// Tech,Crm
mickmackusa
  • 43,625
  • 12
  • 83
  • 136