合并具有相同特定键的数组?

时间:2012-08-07 15:41:55

标签: php arrays multidimensional-array

我有一个数组

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

)

任何人都可以帮我这样做吗?

感谢

3 个答案:

答案 0 :(得分: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'];
}

答案 1 :(得分: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()

Demo

答案 2 :(得分:0)

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

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

OR

$result=array();
while($record=mysql_fetch_assoc($query_result))
{
    $result[$record['id_session']][$record['id_participant']]=$record['participant']; 
}