Domanda

Ho un array associativo nel formato key = > valore dove chiave è un valore numerico, tuttavia non è un valore numerico sequenziale. La chiave è in realtà un numero ID e il valore è un conteggio. Questo va bene per la maggior parte dei casi, tuttavia voglio una funzione che ottenga il nome leggibile dall'array dell'array e lo usi per la chiave, senza cambiare il valore.

Non ho visto una funzione che lo fa, ma presumo che debba fornire la vecchia chiave e la nuova chiave (entrambe le quali ho) e trasformare l'array. Esiste un modo efficace per farlo?

È stato utile?

Soluzione

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);

Altri suggerimenti

Il modo in cui lo faresti e preserveresti l'ordine dell'array è quello di mettere le chiavi dell'array in un array separato, trovare e sostituire la chiave in quell'array e poi ricomporla con i valori.

Ecco una funzione che fa proprio questo:

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

se il tuo array è creato da una query del database, puoi cambiare la chiave direttamente dall'istruzione mysql :

anziché

"select ´id´ from ´tablename´..."

usa qualcosa come:

"select ´id´ **as NEWNAME** from ´tablename´..."

La risposta di KernelM è buona, ma per evitare il problema sollevato da Greg nel commento (chiavi in ??conflitto), usare un nuovo array sarebbe più sicuro

$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);

È possibile utilizzare un secondo array associativo che associa nomi leggibili umani all'ID. Ciò fornirebbe anche una relazione Many to 1. Quindi fai qualcosa del genere:

echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];

Se vuoi che anche la posizione della nuova chiave dell'array sia la stessa di quella precedente puoi farlo:

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

Se l'array è ricorsivo è possibile utilizzare questa funzione: prova questi dati:

    $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,
            )
    );

ecco la funzione:

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;   
}
$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
];
*/

Mi piace la soluzione di KernelM, ma avevo bisogno di qualcosa che potesse gestire potenziali conflitti di chiavi (dove una nuova chiave potrebbe corrispondere a una chiave esistente). Ecco cosa mi è venuto in mente:

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

È quindi possibile scorrere un array come questo:

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

Ecco una funzione di aiuto per raggiungere questo obiettivo:

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

piuttosto basato sulla @KernelM answer .

Utilizzo:

_rename_arr_key('oldkey', 'newkey', $my_array);

Restituirà vero in caso di rinominazione riuscita, altrimenti falso .

Roba facile:

questa funzione accetta l'obiettivo $ hash e $ sostituzioni è anche un hash contenente newkey = > oldkey associazioni .

Questa funzione manterrà l'ordine originale , ma potrebbe essere problematica per array molto grandi (come sopra i record di 10k) riguardanti performance & amp; memoria .

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

questa funzione alternativa farebbe lo stesso, con prestazioni di gran lunga migliori & amp; utilizzo della memoria, a costo di perdere l'ordine originale (che non dovrebbe essere un problema poiché è hashtable!)

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

questo codice aiuterà a cambiare il vecchio in uno nuovo

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

visualizza come

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

funziona per rinominare la prima chiave:

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

quindi, print_r ($ a) esegue il rendering di un array in ordine riparato:

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

funziona per rinominare una chiave arbitraria:

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

una funzione generalizzata:

function renameKey($oldkey, $newkey, $array) {
    $val = $array[$oldkey];
    $tmp_A = array_flip($array);
    $tmp_A[$val] = $newkey;

    return array_flip($tmp_A);
}

Se vuoi sostituire più chiavi contemporaneamente (preservando l'ordine):

/**
 * Rename keys of an array
 * @param array $array (asoc)
 * @param array $replacement_keys (indexed)
 * @return array
 */
function rename_keys($array, $replacement_keys)  {
      return array_combine($replacement_keys, array_values($array));
}

Utilizzo:

$myarr = array("a" => 22, "b" => 144, "c" => 43);
$newkeys = array("x","y","z");
print_r(rename_keys($myarr, $newkeys));
//must return: array("x" => 22, "y" => 144, "z" => 43);

Esiste un modo alternativo per cambiare la chiave di un elemento dell'array quando si lavora con un array completo, senza cambiare l'ordine dell'array. È semplicemente copiare l'array in un nuovo array.

Ad esempio, stavo lavorando con un array misto e multidimensionale che conteneva chiavi indicizzate e associative - e volevo sostituire le chiavi intere con i loro valori, senza interrompere l'ordine.

L'ho fatto cambiando chiave / valore per tutte le voci di array numerici - qui: ['0' = > 'pippo']. Nota che l'ordine è intatto.

<?php
$arr = [
    'foo',
    'bar'=>'alfa',
    'baz'=>['a'=>'hello', 'b'=>'world'],
];

foreach($arr as $k=>$v) {
    $kk = is_numeric($k) ? $v : $k;
    $vv = is_numeric($k) ? null : $v;
    $arr2[$kk] = $vv;
}

print_r($arr2);

Output:

Array (
    [foo] => 
    [bar] => alfa
    [baz] => Array (
            [a] => hello
            [b] => world
        )
)

È possibile utilizzare questa funzione in base a array_walk:

function mapToIDs($array, $id_field_name = 'id')
{
    $result = [];
    array_walk($array, 
        function(&$value, $key) use (&$result, $id_field_name)
        {
            $result[$value[$id_field_name]] = $value;
        }
    );
    return $result;
}

$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));

Dà:

Array(
    [0] => Array(
        [id] => one
        [fruit] => apple
    )
    [1] => Array(
        [id] => two
        [fruit] => banana
    )
)

Array(
    [one] => Array(
        [id] => one
        [fruit] => apple
    )
    [two] => Array(
        [id] => two
        [fruit] => banana
    )
)

Hmm, non ho mai provato prima, ma penso che questo codice funzioni

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

Uno che preserva l'ordinamento che è semplice da capire:

function rename_array_key(array $array, $old_key, $new_key) {
  if (!array_key_exists($old_key, $array)) {
      return $array;
  }
  $new_array = [];
  foreach ($array as $key => $value) {
    $new_key = $old_key === $key
      ? $new_key
      : $key;
    $new_array[$new_key] = $value;
  }
  return $new_array;
}

il modo migliore è usare il riferimento e non usare unset (che fa un altro passo per pulire la memoria)

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

soluzione:

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

hai un originale e un riferimento con un nuovo nome.

o se non vuoi avere due nomi in un valore è buono crea un'altra scheda e foreach su riferimento

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

Iterration è meglio sui tasti rispetto alla clonazione di tutti gli array e alla pulizia di vecchi array se si hanno dati lunghi come 100 righe +++ ecc.

È possibile scrivere una funzione semplice che applica il callback ai tasti dell'array specificato. Simile a array_map

<?php
function array_map_keys(callable $callback, array $array) {
    return array_merge([], ...array_map(
        function ($key, $value) use ($callback) { return [$callback($key) => $value]; },
        array_keys($array),
        $array
    ));
}

$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);

echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}

Ecco un esempio https://gist.github.com/vardius / 650367e15abfb58bcd72ca47eff096ca # file-array_map_keys-php .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top