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

后端 未结 23 2343
逝去的感伤
逝去的感伤 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:20

    You can write simple function that applies the callback to the keys of the given array. Similar to array_map

     $value]; },
            array_keys($array),
            $array
        ));
    }
    
    $array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
    $newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);
    
    echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
    echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}
    

    Here is a gist https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php.

提交回复
热议问题