重命名键并保持排序一致(后者对于以下代码的使用情况很重要)。
<?php
function renameKey(array &$data, $oldKey, $newKey, $ignoreMissing = false, $replaceExisting = false)
{
if (!empty($data)) {
if (!array_key_exists($oldKey, $data)) {
if ($ignoreMissing) {
return false;
}
return !trigger_error('Old key does not exist', E_USER_WARNING);
} else {
if (array_key_exists($newKey, $data)) {
if ($replaceExisting) {
unset($data[$newKey]);
} else {
return !trigger_error('New key already exists', E_USER_WARNING);
}
}
$keys = array_keys($data);
$keys[array_search($oldKey, array_map('strval', $keys))] = $newKey;
$data = array_combine($keys, $data);
return true;
}
}
return false;
}
还有一些单元测试(使用PHPUnit,但希望测试目的易于理解)。
public function testRenameKey()
{
$newData = $this->data;
$this->assertTrue(Arrays::renameKey($newData, 200, 'TwoHundred'));
$this->assertEquals(
[
100 => $this->one,
'TwoHundred' => $this->two,
300 => $this->three,
],
$newData
);
}
public function testRenameKeyWithEmptyData()
{
$newData = [];
$this->assertFalse(Arrays::renameKey($newData, 'junk1', 'junk2'));
}
public function testRenameKeyWithExistingNewKey()
{
Arrays::renameKey($this->data, 200, 200);
$this->assertError('New key already exists', E_USER_WARNING);
}
public function testRenameKeyWithMissingOldKey()
{
Arrays::renameKey($this->data, 'Unknown', 'Unknown');
$this->assertError('Old key does not exist', E_USER_WARNING);
}
public function testRenameKeyWithMixedNumericAndStringIndicies()
{
$data = [
'nice',
'car' => 'fast',
'none',
];
$this->assertTrue(Arrays::renameKey($data, 'car', 2));
$this->assertEquals(
[
0 => 'nice',
2 => 'fast',
1 => 'none',
],
$data
);
}
PHPUnit中的AssertError断言可以从https://github.com/digitickets/phpunit-errorhandler获取。