【问题标题】:PHP/MYSQL Replace text of keys in array of dictionariesPHP/MYSQL 替换字典数组中键的文本
【发布时间】:2019-11-04 05:44:20
【问题描述】:

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

例如,在以下情况:

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

我想改成:

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

在这种情况下,更改 mysql 查询是不切实际的,所以我只想用单词“golfer”替换键的单词“player”而不影响值。

在上面的例子中,我不想改变 Gary Player 的名字,所以仅仅使用 str_replace 似乎行不通。

有没有一种方法可以在不更改任何值的情况下将所有键从“player”更改为“golfer”?

【问题讨论】:

    标签: php mysql arrays dictionary str-replace


    【解决方案1】:

    这是你可以使用的sn-p

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

    Demo & source.

    使用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.

    【讨论】:

      【解决方案2】:
      $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);
      

      【讨论】:

        【解决方案3】:

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

        将名为“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/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-13
          • 1970-01-01
          • 2012-12-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-19
          • 2014-02-05
          相关资源
          最近更新 更多