Created
December 21, 2013 08:10
-
-
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."
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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