基本上我有这个阵列:
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'] );
}
?>
但是当有更多参数时,线条数量巨大。有更简单的方法吗?
答案 0 :(得分:0)
保持数组和unset()
user_id
:
<?php
$newArray = array();
foreach( $array as $data ) {
$newArray[ $data['user_id'] ] = $data;
unset($newArray[$data['user_id']]['user_id']);
}
?>