将多维数字数组转换为关联数组。

时间:2022-10-11 21:18:05

Basicly I've got this array:

我有这个数组:

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

And I would like to use the user_id as array key. So it looks like this:

我想用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
        )
)

I can accomplish that by using the following code.

我可以通过使用以下代码来实现这一点。

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

But when there are more parameters, the amount of lines is huge. Is there an easier way?

但是当有更多的参数时,行数就会很大。有更简单的方法吗?

1 个解决方案

#1


0  

Just keep the array and unset() the user_id:

只保留数组和unset() user_id:

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

}
?>

#1


0  

Just keep the array and unset() the user_id:

只保留数组和unset() user_id:

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

}
?>