Skip to content
Advertisement

In PHP, for a specific key in an associative array, find identical keys and combine values into a single string variable

I have found many references for similar questions on SO but nothing close to what I’m trying to do. I have this array output:

0: {id: 1000012, kp_uid: 100000570, assigned_uid: 'tim.hughes@sampleco.com', full_name: 'Tim Hughes'}
1: {id: 1000013, kp_uid: 100000570, assigned_uid: 'brad.slater@sampleco.com', full_name: 'Brad Slater'}
2: {id: 1000014, kp_uid: 100000570, assigned_uid: 'karen.tevis@sampleco.com', full_name: 'Karen Tevis'}
3: {id: 1000015, kp_uid: 100000597, assigned_uid: 'karen.tevis@sampleco.com', full_name: 'Karen Tevis'}

I would like to now use ‘kp_uid’ to locate all common values and then combine the ‘full_name’ values for each key into a string (with comma separation). Desired outcome from above example will be:

0: {kp_uid: 100000570, full_name: 'Tim Hughes, Brad Slater, Karen Tevis'}
1: {kp_uid: 100000597, full_name: 'Karen Tevis'}

I have tried many ideas gathered from SO and this was the closest but I can’t separate out the unique key:

unset($kp_assign['id']);
unset($kp_assign['assigned_uid']);

$result = array();
foreach ($kp_assign as $arr) {
    foreach($arr as $key => $val) {
        $result[$key][] = $val;
    }
}
return $result;

Partial results from this show all four names:

full_name: Array(4)
0: "Tim Hughes"
1: "Brad Slater"
2: "Karen Tevis"
3: "Karen Tevis"

Any direction here will be appreciated. Thank you.

Advertisement

Answer

$items = [
    ['id' => 1000012, 'kp_uid' => 100000570, 'assigned_uid' => 'tim.hughes@sampleco.com', 'full_name' => 'Tim Hughes'],
    ['id' => 1000013, 'kp_uid' => 100000570, 'assigned_uid' => 'brad.slater@sampleco.com', 'full_name' => 'Brad Slater'],
    ['id' => 1000014, 'kp_uid' => 100000570, 'assigned_uid' => 'karen.tevis@sampleco.com', 'full_name' => 'Karen Tevis'],
    ['id' => 1000015, 'kp_uid' => 100000597, 'assigned_uid' => 'karen.tevis@sampleco.com', 'full_name' => 'Karen Tevis']
];

$grouped = [];

// group items by kp_uid
foreach ($items as $item) {
    $grouped[$item['kp_uid']][] = $item;
}

function mapNamesCallback($item)
{
    return $item['full_name'];
}

// iterate over groups and return a single item
// in form of kp_uid => x, full_names => 'name, name2 etc.'
$result = array_map(function ($group, $kpUid) {
    return ['kp_uid' => $kpUid, 'full_name' => implode(', ', array_map('mapNamesCallback', $group))];
}, $grouped, array_keys($grouped));

This returns desired result. I left a few comments in the code for clarity.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement