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

2 Answers 2

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 ,.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.