1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
<?php
$json = '[ {"Prenom":"John", "Nom":"Doe", "Tel":"0600000000"}, {"Prenom":"John", "Nom":"Smith", "Tel":"0600000000"} ]';
/* Tableau de correspondance entre les anciennes et nouvelles clés. */
$newJson = alterKeysJson($json, [
'Nom' => 'Sub_title',
'Tel' => 'Number'
]);
var_dump($newJson);
// Le resultat du changement des clés.
//"[
// {"Prenom":"John","Sub_title":"Doe","Number":"0600000000"},
// {"Prenom":"John","Sub_title":"Smith","Number":"0600000000"}
//]"
function alterKeysJson($json, array $alterKeys)
{
$array = json_decode($json, true);
foreach($alterKeys as $oldKey => $newKey)
{
$array = alterKeyArray($array, $oldKey, $newKey);
}
return json_encode($array);
}
function alterKeyArray(array $array, $oldKey, $newKey)
{
foreach($array as &$value) {
if (isset($value[$oldKey])) {
$value[$newKey] = $value[$oldKey];
unset($value[$oldKey]);
}
}
return $array;
} |
Partager