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

后端 未结 23 2331
逝去的感伤
逝去的感伤 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: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;   
    }
    

提交回复
热议问题