2012-02-27 56 views
1

我有一個數組,其中包含一個以逗號分隔的數組中的PID,電子郵件和客戶端列表。我想知道是否有辦法解析輸入數組並生成一個具有「Email」作爲該電子郵件的密鑰和所有唯一PID的新數組。由於輸入數組可以有數千個元素,所以我想知道最快的方法。使用輸入數組中的鍵構造陣列

Ex: Input Array (PID, Email, Client) 
-------------------------------------- 
Array ( 
[0] => 10, [email protected],Gmail 
[1] => 11, [email protected],Gmail 
[2] => 12, [email protected],Gmail 
[3] => 13, [email protected],Gmail 
[4] => 14, [email protected],Gmail 
[5] => 15, [email protected],Gmail 
) 


Ex: Output Array (with Email as the key): 
--------------------------------------------- 
Array (
[[email protected]] => (
        [0] => 10 
       [1] => 12 
     ), 
[[email protected]] => (
       [0] => 11 
       [1] => 13 
       [2] => 15 
     ), 
[[email protected]] => (
       [0] => 14 
     ) 
) 

感謝

+1

的foreach(),然後發生爆炸()在逗號 – 2012-02-27 19:52:41

+0

哪兒來的逗號分隔陣列來自?你是否在CSV文件中調用'fgets()'? – 2012-02-27 20:28:07

+0

no..came從數據庫 – Jake 2012-02-27 21:59:35

回答

3
// $input holds your initial array: 
// $ouput is output... 
$output = array(); 
foreach ($input as $arr) { 
    // Explode the comma-delimited lines into 3 vars 
    list($pid, $email, $client) = explode(",", $arr); 
    // Initialize a new array for the Email key if it doesn't exist 
    if (!isset($output[$email])) $output[$email] = array(); 
    // Append the PID to the Email key 
    $output[$email][] = $pid; 
} 
0
$emails = array(); 

foreach($array as $item){ 
    $data = explode(",", $item); 
    $id = trim($data[0]); 
    $email = trim($data[1]); 
    if (!isset($emails[ $email ]){ $emails[ $email ] = array(); } 
    array_push($emails[ $email ], $id); 
} 
1

我能想到的唯一的辦法是這樣的:

$outputArray = array(); 
foreach ($inputArray as $value) 
{ 
    list($pid, $email) = explode(",", trim($value)); 
    $outputArray[$email][] = $pid; 
}