我有一个形式key =>值的关联数组,其中key是一个数值,但它不是一个连续的数值。键实际上是一个ID号,值是一个计数。这对于大多数实例来说都很好,但是我想要一个函数获得人类可读的数组名称并将其用作键,而不更改值。

我没有看到这样做的函数,但我假设我需要提供旧键和新键(我都有)并转换数组。有没有一种有效的方法来做到这一点?


当前回答

这段代码将帮助将旧密钥更改为新密钥

$i = 0;
$keys_array=array("0"=>"one","1"=>"two");

$keys = array_keys($keys_array);

for($i=0;$i<count($keys);$i++) {
    $keys_array[$keys_array[$i]]=$keys_array[$i];
    unset($keys_array[$i]);
}
print_r($keys_array);

显示如

$keys_array=array("one"=>"one","two"=>"two");

其他回答

我喜欢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;
    }
}

然后你可以像这样循环数组:

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

简单的东西:

此函数将接受目标$哈希值,$replacement也是包含newkey=>oldkey关联的哈希值。

这个函数将保留原始顺序,但对于非常大的数组(比如超过10k的记录),在性能和内存方面可能会有问题。

function keyRename(array $hash, array $replacements) {
    $new=array();
    foreach($hash as $k=>$v)
    {
        if($ok=array_search($k,$replacements))
            $k=$ok;
        $new[$k]=$v;
    }
    return $new;    
}

这个替代函数也会做同样的事情,具有更好的性能和内存使用,代价是失去原来的顺序(这应该不是问题,因为它是哈希表!)

function keyRename(array $hash, array $replacements) {

    foreach($hash as $k=>$v)
        if($ok=array_search($k,$replacements))
        {
          $hash[$ok]=$v;
          unset($hash[$k]);
        }

    return $hash;       
}

最好的方法是使用引用,而不是使用unset(这是清理内存的另一个步骤)

$tab = ['two' => [] ];

解决方案:

$tab['newname'] = & $tab['two'];

你有一份原件和一份有新名字的参考资料。

或者如果你不想在一个值中有两个名字是很好的,让另一个TAB和foreach引用

foreach($tab as $key=> & $value) {
    if($key=='two') { 
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}

迭代键比克隆所有数组更好,如果你有长数据,如100行+++等,清洗旧数组。

嗯,我没有测试之前,但我认为这段代码工作

function replace_array_key($data) {
    $mapping = [
        'old_key_1' => 'new_key_1',
        'old_key_2' => 'new_key_2',
    ];

    $data = json_encode($data);
    foreach ($mapping as $needed => $replace) {
        $data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
    }

    return json_decode($data, true);
}

这个函数将通过结合索引搜索来重命名数组键,并保持其位置。

function renameArrKey($arr, $oldKey, $newKey){
    if(!isset($arr[$oldKey])) return $arr; // Failsafe
    $keys = array_keys($arr);
    $keys[array_search($oldKey, $keys)] = $newKey;
    $newArr = array_combine($keys, $arr);
    return $newArr;
}

用法:

$arr = renameArrKey($arr, 'old_key', 'new_key');