sblumberg sblumberg - 22 days ago 14
PHP Question

Need a way to output merged content from two arrays

I have two very large arrays I want to recognize where it finds duplicates on the first array, and merges them with the exact array position in another array, and append the value with a comma. I simply cannot wrap my head around how to do it.

//array with the multiple entries.
$applicationid = array('1','1','2','3','3','4','5','6','6','7','8','9','10','11','12','13','13','14','14','15','16','17','18','18');
$applicantid = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','11','22','25');


Easily viewed it looks like this when put side by side.

applicationid on left. applicantid on right.
1 1
1 2
2 3
3 4
3 5
4 6
5 7
6 8
6 9
7 10
8 11
9 12
10 13
11 14
12 15
13 16
13 17
14 18
14 19
15 20
16 21
17 11
18 22
18 25


I would like the end result to be for these two arrays:

[1]['1,2']
[2]['3']
[3]['4,5']
[4]['6']
[5]['7']
[6]['8,9']
[7]['10']
[8]['11']
[9]['12']
[10]['13']
[11]['14']
[12]['15']
[13]['16,17']
[14]['18,19']
[15]['20']
[16]['21']
[17]['11']
[18]['22,25']


I'm sure this is easy for someone out there but I cannot seem to be able to wrap my head around it or understand the syntax required.

Additionally just to note the arrays are much bigger than this (roughly 1400 or so entries).

Answer

It's quite simple. That's very convenient that indexes match (whilst it says that the data is generated in a not very suitable format).

Try merging them like this:

$applicationid = array('1','1','2','3','3','4','5','6','6','7','8','9','10','11','12','13','13','14','14','15','16','17','18','18');
$applicantid = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','11','22','25');

$applicantsByApplications = [];
$applicantsCount = count($applicationid);
for ($i = 0; $i < $applicantsCount; $i++)
{
    $applicant = $applicantid[$i];
    $application = $applicationid[$i];
    if (!isset($applicantsByApplications[$application]))
        $applicantsByApplications[$application] = [];
    $applicantsByApplications[$application][] = $applicant;
}

This can be beautified using standard functions, array_map etc., but the principle stays the same.

Comments