user1274113
user1274113

Reputation: 446

Combine array with same element value and keep them all together

I have this array:

[0] => Array
    (
        [userid] => 208
        [username] => sara
        [email] => [email protected]
    )

[1] => Array
    (
        [userid] => 4
        [username] => jack
        [email] => [email protected]
    )

[2] => Array
    (
        [userid] => 303
        [username] => michael
        [email] => [email protected]
    )

[3] => Array
    (
        [userid] => 208
        [username] => joe
        [email] => [email protected]
    )

[4] => Array
    (
        [userid] => 208
        [username] => david
        [email] => [email protected]
    )

And i want this result:

[0] => Array
(
    [userid] => 208
    [username1] => sara
    [username2] => joe 
    [username3] => david
    [email1] => [email protected]
    [email2] => [email protected]
    [email3] => [email protected]
)

[1] => Array
(
    [userid] => 4
    [username1] => jack
    [email1] => [email protected]
)

[2] => Array
(
    [userid] => 303
    [username1] => michael
    [email1] => [email protected]
)

I'm trying to array_combine, array_merge and even array_unique with several foreach plus $n++; cycle with no success. More precisly i succeeded but changing the entire structure of the array.

Upvotes: 1

Views: 2557

Answers (2)

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

you could do:

/* $myArray is the array you are trying to change */
$result = array(); //Your minimized array
foreach($myArray as $value){
    $userid = $value['userid'];
    if(isset($result[$userid]))
        $index = ((count($result[$userid]) - 1) / 2) + 1;
    else
        $index = 1;

    $result[$userid]['userid'] = $userid;
    $result[$userid]['username' . $index] = $value['username'];
    $result[$userid]['email' . $index] = $value['email'];        
}
$result = array_values($result);

Upvotes: 2

dikirill
dikirill

Reputation: 1903

I have to loop thru array to build desired structure:

$result = array();
foreach($data as $item) {
   $result[$item['userid']]['userid'] = $item['userid'];
   $i = 1;
   while (true) {
       if (!isset($result[$item['userid']]['username' . $i])) {
           $result[$item['userid']]['username' . $i] = $item['username'];
           $result[$item['userid']]['email' . $i] = $item['email'];
           break;
       }
       $i++;
   }
}
var_dump($result);

Upvotes: 1

Related Questions