2016-11-10 43 views
0

我有兩個非常大的數組,我想識別它在第一個數組上找到重複的位置,並將它們與另一個數組中的精確數組位置合併,並將該值附加到逗號。我根本無法圍繞如何去做。需要一種方法來輸出來自兩個陣列的合併內容

//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'); 

容易地看到它看起來像這樣並排放置時。

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 

我想最終的結果是對於這兩個數組:

[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'] 

我敢肯定,這很容易讓一個人在那裏,但我不能似乎能夠繞到我的頭它或理解所需的語法。

此外,只是爲了說明數組比這大得多(大約1400條左右)。

回答

2

這很簡單。索引匹配非常方便(雖然它表示數據是以非常合適的格式生成的)。

嘗試將它們合併這樣的:

$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; 
} 

這可以使用標準功能,array_map等被美化,但原則保持不變。

+0

您的輸出不是預期的輸出 –

+0

對不起,沒有用PHP運行時檢查代碼:-( 現在全部都修好了 – BVengerov

+0

不幸的是如此接近!儘管是否存在重複,輸出仍然保持最初的數字 – sblumberg

相關問題