1

I have an array that has a list of PID, Email and Client in a comma delimited array. I was wondering if there's a way to parse the input array and generate a new array that has "Email" as the key and all unique PIDs for that email. Since the input array can have thousands of elements, I was wondering about the fastest approach.

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
          )
)

Thanks

2
  • 1
    foreach() then explode() on comma Commented Feb 27, 2012 at 19:52
  • Where did the comma-delimited array come from? Are you calling fgets() on a CSV file? Commented Feb 27, 2012 at 20:28

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Only way I can think of is this:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.