0

I have a MYSQL query that fetches an array of dictionaries or results which are returned via JSON in an api. In some cases, I would like to change the name of the dictionary keys in the results array.

For example, in the following case:

$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';

I would like to change it to:

$var = '[{"golfer":"Tiger Woods"},{"golfer":"Gary Player"}]'

It is not practical in this case to change the mysql query so I'd just like to replace the word "player" with the word "golfer" for the keys without disturbing the values.

In the above example, I would not want to change Gary Player's name so just using str_replace does not seem like it would work.

Is there a way to change all of the keys from "player" to "golfer" without changing any of the values?

zztop
  • 701
  • 1
  • 7
  • 20

3 Answers3

4

Here is the snippet you can use

$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
// json decode the json string
$temp = json_decode($var, true);
$temp = array_map(function($item){
    // combining key and values
    return array_combine(['golfer'], $item);
}, $temp);
print_r($temp);
// or echo json_encode($temp);

Demo.

Some argue that foreach is fastest,

foreach($temp as $k => &$v){
     $v = array_combine(['golfer'], $v);
}
print_r($temp);

Demo.

Little hardcoded if more than one keys in single array,

foreach ($temp as $k => &$v){
  $v['golfer'] = $v['player'];
  unset($v['player']);
}
print_r($temp);

Demo.

Using recursion

function custom($arr, $newKey, $oldKey)
{
    // if the value is not an array, then you have reached the deepest
    // point of the branch, so return the value
    if (!is_array($arr)) {
        return $arr;
    }

    $result = []; // empty array to hold copy of subject
    foreach ($arr as $key => $value) {
        // replace the key with the new key only if it is the old key
        $key = ($key === $oldKey) ? $newKey : $key;
        // add the value with the recursive call
        $result[$key] = custom($value, $newKey, $oldKey);
    }
    return $result;
}
$var  = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$temp = json_decode($var, true);
$temp = replaceKey($temp, 'golfer', 'player');
print_r($temp);

Demo & source.

Using json way,

function json_change_key($arr, $oldkey, $newkey) {
    $json = str_replace('"'.$oldkey.'":', '"'.$newkey.'":', json_encode($arr));
    return json_decode($json, true);    
}
$temp = json_change_key($temp, 'player', 'golfer');
print_r($temp);

Demo
If you want multiple key replace, here is the trick,

$var = '[{"player":"Tiger Woods", "wins":"10","losses":"3"},{"player":"Gary Player","wins":"7", "losses":6}]';
$temp = json_decode($var, true);
function recursive_change_key($arr, $set)
{
    if (is_array($arr) && is_array($set)) {
        $newArr = [];
        foreach ($arr as $k => $v) {
            $key          = array_key_exists($k, $set) ? $set[$k] : $k;
            $newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;
        }
        return $newArr;
    }
    return $arr;
}
$set = [
    "player" => "golfers",
    "wins" => "victories",
    "losses" => "defeats"
    ];
$temp = recursive_change_key($temp, $set);
print_r($temp);

Demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60
4
$a = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';

$array = json_decode($a, true);


foreach($array as $key=>$value){

    if(array_keys($value)[0] === "player"){
        $array[$key] = ["golfer" => array_values($value)[0]];
    };

}   

echo json_encode($array);
0

you can write the value of the key to a new key and then delete the old.

renaming a key called "a" to "b", while keeping the value.


var json = {
    "a" : "one"
}

json["b"] = json["a"];
delete json["a"];

for your example, just use this with a loop.

source: https://sciter.com/forums/topic/how-to-rename-the-key-of-json/

Mapijs
  • 45
  • 7