将多维数字数组更改为关联数组

时间:2015-08-23 18:05:04

标签: php arrays

基本上我有这个阵列:

Array
(
    [0] => Array
        (
            [user_id] => 15
            [username] => test user 1
            [user_email] => test1@mail.com
        )
    [1] => Array
        (
            [user_id] => 19
            [username] => test user 2
            [user_email] => test2@mail.com
        )
)

我想使用user_id作为数组键。所以它看起来像这样:

Array
(
    [15] => Array
        (
            [username] => test user 1
            [user_email] => test1@mail.com
        )
    [19] => Array
        (
            [username] => test user 2
            [user_email] => test2@mail.com
        )
)

我可以使用以下代码完成此操作。

<?php
$newArray = array();
foreach( $array as $data ) {
    $newArray[ $data['user_id'] ] = array(
        'username'=> $data['username'],
        'user_email' => $data['user_email'] );
}
?>

但是当有更多参数时,线条数量巨大。有更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

保持数组和unset() user_id

<?php
$newArray = array();
foreach( $array as $data ) {
    $newArray[ $data['user_id'] ] = $data;
    unset($newArray[$data['user_id']]['user_id']);

}
?>