1

我有这个数组:

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

我正在尝试将 array_combine、array_merge 甚至 array_unique 与几个 foreach 加 $n++; 循环没有成功。更准确地说,我成功了,但改变了数组的整个结构。

4

2 回答 2

2

你可以这样做:

/* $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);
于 2013-04-25T15:53:06.387 回答
1

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

$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);
于 2013-04-25T15:50:03.833 回答