在 PHP 中,如何更改数组元素的键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/240660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In PHP, how do you change the key of an array element?
提问by Thomas Owens
I have an associative array in the form key => valuewhere key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.
我有一个关联数组,key => value其中 key 是一个数值,但它不是一个连续的数值。键实际上是一个 ID 号,而值是一个计数。这对于大多数情况来说都很好,但是我想要一个函数来获取数组的可读名称并将其用于键,而不更改值。
I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?
我没有看到执行此操作的函数,但我假设我需要提供旧密钥和新密钥(我都有)并转换数组。有没有一种有效的方法来做到这一点?
回答by KernelM
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
回答by DiverseAndRemote.com
The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.
执行此操作并保留数组顺序的方法是将数组键放入单独的数组中,查找并替换该数组中的键,然后将其与值合并。
Here is a function that does just that:
这是一个可以做到这一点的函数:
function change_key( $array, $old_key, $new_key ) {
if( ! array_key_exists( $old_key, $array ) )
return $array;
$keys = array_keys( $array );
$keys[ array_search( $old_key, $keys ) ] = $new_key;
return array_combine( $keys, $array );
}
回答by Simon Franco
if your arrayis built from a database query, you can change the key directly from the mysqlstatement:
如果您array是从数据库查询构建的,则可以直接从mysql语句中更改键:
instead of
代替
"select ′id′ from ′tablename′..."
use something like:
使用类似的东西:
"select ′id′ **as NEWNAME** from ′tablename′..."
回答by kjg
The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer
KernelM 的答案很好,但为了避免 Greg 在评论中提出的问题(冲突的键),使用新数组会更安全
$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);
回答by Tom Ritter
You could use a second associative array that maps human readable names to the id's. That would also provide a Many to 1 relationship. Then do something like this:
您可以使用第二个关联数组将人类可读的名称映射到 ID。这也将提供多对一的关系。然后做这样的事情:
echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];
echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];
回答by spreadzz
If you want also the position of the new array key to be the same as the old one you can do this:
如果您还希望新数组键的位置与旧数组键的位置相同,您可以执行以下操作:
function change_array_key( $array, $old_key, $new_key) {
if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; }
if(!array_key_exists($old_key, $array)){
return $array;
}
$key_pos = array_search($old_key, array_keys($array));
$arr_before = array_slice($array, 0, $key_pos);
$arr_after = array_slice($array, $key_pos + 1);
$arr_renamed = array($new_key => $array[$old_key]);
return $arr_before + $arr_renamed + $arr_after;
}
回答by pajafumo
If your array is recursive you can use this function: test this data:
如果你的数组是递归的,你可以使用这个函数:测试这个数据:
$datos = array
(
'0' => array
(
'no' => 1,
'id_maquina' => 1,
'id_transaccion' => 1276316093,
'ultimo_cambio' => 'asdfsaf',
'fecha_ultimo_mantenimiento' => 1275804000,
'mecanico_ultimo_mantenimiento' =>'asdfas',
'fecha_ultima_reparacion' => 1275804000,
'mecanico_ultima_reparacion' => 'sadfasf',
'fecha_siguiente_mantenimiento' => 1275804000,
'fecha_ultima_falla' => 0,
'total_fallas' => 0,
),
'1' => array
(
'no' => 2,
'id_maquina' => 2,
'id_transaccion' => 1276494575,
'ultimo_cambio' => 'xx',
'fecha_ultimo_mantenimiento' => 1275372000,
'mecanico_ultimo_mantenimiento' => 'xx',
'fecha_ultima_reparacion' => 1275458400,
'mecanico_ultima_reparacion' => 'xx',
'fecha_siguiente_mantenimiento' => 1275372000,
'fecha_ultima_falla' => 0,
'total_fallas' => 0,
)
);
here is the function:
这是功能:
function changekeyname($array, $newkey, $oldkey)
{
foreach ($array as $key => $value)
{
if (is_array($value))
$array[$key] = changekeyname($value,$newkey,$oldkey);
else
{
$array[$newkey] = $array[$oldkey];
}
}
unset($array[$oldkey]);
return $array;
}
回答by temuri
$array = [
'old1' => 1
'old2' => 2
];
$renameMap = [
'old1' => 'new1',
'old2' => 'new2'
];
$array = array_combine(array_map(function($el) use ($renameMap) {
return $renameMap[$el];
}, array_keys($array)), array_values($array));
/*
$array = [
'new1' => 1
'new2' => 2
];
*/
回答by kenorb
Here is a helper function to achieve that:
这是一个帮助函数来实现:
/**
* Helper function to rename array keys.
*/
function _rename_arr_key($oldkey, $newkey, array &$arr) {
if (array_key_exists($oldkey, $arr)) {
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
return TRUE;
} else {
return FALSE;
}
}
pretty based on @KernelM answer.
漂亮基于@KernelM 回答。
Usage:
用法:
_rename_arr_key('oldkey', 'newkey', $my_array);
It will return trueon successful rename, otherwise false.
成功重命名时返回true,否则返回false。
回答by kingjeffrey
I like KernelM's solution, but I needed something that would handle potential key conflicts (where a new key may match an existing key). Here is what I came up with:
我喜欢 KernelM 的解决方案,但我需要一些可以处理潜在密钥冲突的东西(新密钥可能与现有密钥匹配)。这是我想出的:
function swapKeys( &$arr, $origKey, $newKey, &$pendingKeys ) {
if( !isset( $arr[$newKey] ) ) {
$arr[$newKey] = $arr[$origKey];
unset( $arr[$origKey] );
if( isset( $pendingKeys[$origKey] ) ) {
// recursion to handle conflicting keys with conflicting keys
swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );
unset( $pendingKeys[$origKey] );
}
} elseif( $newKey != $origKey ) {
$pendingKeys[$newKey] = $origKey;
}
}
You can then cycle through an array like this:
然后,您可以像这样循环遍历数组:
$myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );
$pendingKeys = array();
foreach( $myArray as $key => $myArrayValue ) {
// NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)
$timestamp = strtotime( $myArrayValue );
swapKeys( $myArray, $key, $timestamp, $pendingKeys );
}
// RESULT: $myArray == array( 1=>'1970-01-01 00:00:01', 60=>'1970-01-01 00:01:00' )

