In PHP, how do you change the key of an array element?

后端 未结 23 2330
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  隐瞒了意图╮
    2020-11-22 04:17

    Hmm, I'm not test before, but I think this code working

    function replace_array_key($data) {
        $mapping = [
            'old_key_1' => 'new_key_1',
            'old_key_2' => 'new_key_2',
        ];
    
        $data = json_encode($data);
        foreach ($mapping as $needed => $replace) {
            $data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
        }
    
        return json_decode($data, true);
    }
    

提交回复
热议问题