简体   繁体   中英

Combine array with same element value and keep them all together

I have this array:

[0] => Array
    (
        [userid] => 208
        [username] => sara
        [email] => sara@sara.com
    )

[1] => Array
    (
        [userid] => 4
        [username] => jack
        [email] => jack@jack.com
    )

[2] => Array
    (
        [userid] => 303
        [username] => michael
        [email] => michael@michael.com
    )

[3] => Array
    (
        [userid] => 208
        [username] => joe
        [email] => joe@joe.com
    )

[4] => Array
    (
        [userid] => 208
        [username] => david
        [email] => david@david.com
    )

And i want this result:

[0] => Array
(
    [userid] => 208
    [username1] => sara
    [username2] => joe 
    [username3] => david
    [email1] => sara@sara.com
    [email2] => joe@joe.com
    [email3] => david@david.com
)

[1] => Array
(
    [userid] => 4
    [username1] => jack
    [email1] => jack@jack.com
)

[2] => Array
(
    [userid] => 303
    [username1] => michael
    [email1] => michael@michael.com
)

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM