In PHP, how do you change the key of an array element?

后端 未结 23 2336
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

相关标签:
23条回答
  • 2020-11-22 04:23

    Simple benchmark comparison of both solution.

    Solution 1 Copy and remove (order lost) https://stackoverflow.com/a/240676/1617857

    for ($i =0; $i < 100000000; $i++){
        $array = ['test' => 'value'];
        $array['test2'] = $array['test'];
        unset($array['test']);
    }
    

    Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857

    for ($i =0; $i < 100000000; $i++){
        $array = ['test' => 'value'];
        $keys = array_keys( $array );
        $keys[array_search('test', $keys, true)] = 'test2';
        array_combine( $keys, $array );
    }
    

    Results:

    php solution1.php  6.33s  user 0.02s system 99% cpu 6.356  total
    php solution1.php  6.37s  user 0.01s system 99% cpu 6.390  total
    php solution2.php  12.14s user 0.01s system 99% cpu 12.164 total
    php solution2.php  12.57s user 0.03s system 99% cpu 12.612 total
    
    0 讨论(0)
  • 2020-11-22 04:23

    best way is using reference, and not using unset (which make another step to clean memory)

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

    solution:

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

    you have one original and one reference with new name.

    or if you don't want have two names in one value is good make another tab and foreach on reference

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

    Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..

    0 讨论(0)
  • 2020-11-22 04:24

    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;   
    }
    
    0 讨论(0)
  • 2020-11-22 04:25

    This function will rename an array key, keeping its position, by combining with index searching.

    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;
    }
    

    Usage:

    $arr = renameArrKey($arr, 'old_key', 'new_key');
    
    0 讨论(0)
  • 2020-11-22 04:26
    $arr[$newkey] = $arr[$oldkey];
    unset($arr[$oldkey]);
    
    0 讨论(0)
  • 2020-11-22 04:28

    this works for renaming the first key:

    $a = ['catine' => 'cat', 'canine'  => 'dog'];
    $tmpa['feline'] = $a['catine'];
    unset($a['catine']);
    $a = $tmpa + $a;
    

    then, print_r($a) renders a repaired in-order array:

    Array
    (
        [feline] => cat
        [canine] => dog
    )
    

    this works for renaming an arbitrary key:

    $a = ['canine'  => 'dog', 'catine' => 'cat', 'porcine' => 'pig']
    $af = array_flip($a)
    $af['cat'] = 'feline';
    $a = array_flip($af)
    

    print_r($a)

    Array
    (
        [canine] => dog
        [feline] => cat
        [porcine] => pig
    )
    

    a generalized function:

    function renameKey($oldkey, $newkey, $array) {
        $val = $array[$oldkey];
        $tmp_A = array_flip($array);
        $tmp_A[$val] = $newkey;
    
        return array_flip($tmp_A);
    }
    
    0 讨论(0)
提交回复
热议问题