0

我有一个数组

Array
(
    [0] => Array
        (
            [id_session] => 174
            [id_participant] => 191
            [participant] => A[mail1@xy.com]
        )

    [1] => Array
        (
            [id_session] => 175
            [id_participant] => 177
            [participant] => B[mail2@xy.com]
        )

    [2] => Array
        (
            [id_session] => 175
            [id_participant] => 189
            [participant] => C[mail3@xy.com]
        )

)

我想获取 json 或多个暗淡数组

Array
(
    [174] => Array([191]=>A[mail1@xy.com]),
    [175] => Array
        (            
            [177] => B[mail2@xy.com],
            [189] => C[mail3@xy.com]
        )

)

任何人都可以帮助我如何做到这一点?

谢谢

4

3 回答 3

1
$new_array = array();
foreach($old_array as $inner_array) {
    if(!isset($new_array[$inner_array['id_session']]))
        $new_array[$inner_array['id_session']] = array();
    $new_array[$inner_array['id_session']][] = $inner_array['participant'];
}
于 2012-08-07T15:48:03.930 回答
1
// initialize the array which will contain the result
$resultArray = [];
foreach($sourceArray as $item) {
    // if there is no item in the array with the session is init the item
    if (!array_key_exists($item['id_session'], $resultArray)) {
        $resultArray[$item['id_session']] = [];
    }

    // add the item to the result
    $resultArray[$item['id_session']][$item['id_participant']] = $item['participant'];
}

请注意,我使用了新的数组语法。如果您使用的是 PHP < 5.4,则应替换[]array().

演示

于 2012-08-07T15:54:44.367 回答
0

其中 $result 将是您的新结构,而 $array 是您现有的结构:

 $result=array();
 foreach($array as $record)
 {
    $result[$record['id_session']][$record['id_participant']]=$record['participant']; 
 }

或者

$result=array();
while($record=mysql_fetch_assoc($query_result))
{
    $result[$record['id_session']][$record['id_participant']]=$record['participant']; 
}
于 2012-08-07T15:47:21.280 回答