将具有相同元素值的数组合并并将它们保持在一起

时间:2013-04-25 15:42:03

标签: php arrays merge

我有这个数组:

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

我想要这个结果:

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

我正在尝试使用几个foreach加$ n ++来使用array_combine,array_merge甚至array_unique;循环没有成功。更准确地说,我成功了,但改变了阵列的整个结构。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

/* $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);

答案 1 :(得分:0)

我必须循环通过数组来构建所需的结构:

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