Skip to content

Instantly share code, notes, and snippets.

@real34
Created December 21, 2013 08:10
Show Gist options
  • Save real34/8066775 to your computer and use it in GitHub Desktop.
Save real34/8066775 to your computer and use it in GitHub Desktop.
Approche naïve de réponse à un question sur la ML AFUP : "Bonjour, je cherche un moyen propre et générique pour remplacer les clés d'un tableau associatif par une autre en gardant exactement la même structure pour la sortie."
<?php
$initial = array(
array(
'idcom' => 2,
'idcatalog' => 1,
'pseudo_com' => 'babar'
),
array(
'idcom' => 1,
'idcatalog' => 1,
'pseudo_com' => 'gtraxx'
)
);
$expected = array(
array(
'id' => 2,
'catalog' => 1,
'name' => 'babar'
),
array(
'id' => 1,
'catalog' => 1,
'name' => 'gtraxx'
)
);
function keysConverter($keysMapping) {
return function ($source) use ($keysMapping) {
$result = [];
foreach ($keysMapping as $sourceKey => $destKey) {
$result[$destKey] = $source[$sourceKey];
}
return $result;
};
}
$mapping = ['idcom' => 'id', 'idcatalog' => 'catalog', 'pseudo_com' => 'name'];
$converter = keysConverter($mapping);
$result = array_map($converter, $initial);
if ($expected === $result) {
die('OK');
} else {
var_dump($result);
die('NOT OK');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment