使用Input数组中的键构造数组

时间:2012-02-27 19:49:49

标签: php

我有一个数组,其中包含逗号分隔数组中的PID,电子邮件和客户端列表。我想知道是否有办法解析输入数组并生成一个新的数组,其中包含“Email”作为密钥以及该电子邮件的所有唯一PID。由于输入数组可以包含数千个元素,因此我想知道最快的方法。

Ex: Input Array (PID, Email, Client)
--------------------------------------
Array ( 
[0] => 10, abc@test.com,Gmail 
[1] => 11, def@test.com,Gmail
[2] => 12, abc@test.com,Gmail 
[3] => 13, def@test.com,Gmail
[4] => 14, xyz@test.com,Gmail 
[5] => 15, def@test.com,Gmail
)


Ex: Output Array (with Email as the key):
---------------------------------------------
Array (
[abc@test.com] => (
                   [0] => 10
               [1] => 12
          ),
[def@test.com] => (
               [0] => 11
               [1] => 13
               [2] => 15
          ),
[xyz@test.com] => (
               [0] => 14
          )
)

由于

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

我能想到的只有这样:

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

答案 2 :(得分: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 );
}