PHP / MYSQL替换字典数组中的键文本

时间:2019-06-21 11:12:29

标签: php mysql arrays dictionary str-replace

我有一个MYSQL查询,该查询可获取字典或通过api中的JSON返回的结果数组。在某些情况下,我想更改结果数组中字典键的名称。

例如,在以下情况下:

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

我想将其更改为:

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

在这种情况下,更改mysql查询是不切实际的,因此我只想在不打扰值的情况下将单词“ player”替换为单词“ golfer”。

在上面的示例中,我不想更改Gary Player的名称,因此仅使用str_replace似乎不可行。

是否可以在不更改任何值的情况下将所有键从“玩家”更改为“高尔夫球手”?

3 个答案:

答案 0 :(得分:4)

这是您可以使用的代码段

$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

有人认为foreach最快,

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

Demo

如果单个数组中有多个键,则几乎没有硬编码

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

Demo

使用递归

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

Demosource

使用json方式,

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
如果要替换多个键,这是窍门,

$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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

您可以将密钥的值写入新密钥,然后删除旧密钥。

在保留值的同时将名为“ a”的键重命名为“ b”。


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

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

例如,只需将其与循环一起使用。

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