在PHP中更改关联数组中的键
假设我有这样一个数组:在PHP中更改关联数组中的键,php,arrays,associative-array,Php,Arrays,Associative Array,假设我有这样一个数组: array(2) { [0]=> array(2) { ["n"]=> string(4) "john" ["l"]=> string(3) "red" } [1]=> array(2) { ["n"]=> string(5) "nicel" ["l"]=> string(4) "blue" } } 如何更改内部阵列的键?比如说,我想把“n”改成“name”,把“l”改成“last_na
array(2) {
[0]=> array(2) {
["n"]=> string(4) "john"
["l"]=> string(3) "red"
}
[1]=> array(2) {
["n"]=> string(5) "nicel"
["l"]=> string(4) "blue"
}
}
如何更改内部阵列的键?比如说,我想把“n”改成“name”,把“l”改成“last_name”。考虑到数组可能没有特定的键。只需记下旧值,使用将其从数组中删除,然后将其与新键和旧值对一起添加。类似的内容可能:
if (isset($array['n'])) {
$array['name'] = $array['n'];
unset($array['n']);
}
注意:此解决方案将更改键的顺序。要保留顺序,您必须重新创建阵列。您可以:
$mapKeyArray
变量添加一对键/值,就可以进行其他替换
如果原始阵列中的某个键不可用,此解决方案也可以使用此功能:
$original=array('n'=>'john','l'=>'red');
$flipped=数组_flipe($original);
foreach($k=>v){
$flipped[$k]=($v==='n'?'name':($v==='l'?'last_name':$v));
}
$correctedOriginal=array\u flip($fliped);
使用数组
array_walk($array, function (& $item) {
$item['new_key'] = $item['old_key'];
unset($item['old_key']);
});
重命名密钥并保持顺序一致(后者对于编写以下代码的用例非常重要)
AssertError断言可从为PHPUnit提供。这里有一个更改数组键的解决方案,也可以保持数组中的原始位置。它用于关联数组。在我的例子中,值是对象,但我简化了这个例子
// Our array
$fields = array(
'first_name' => 'Radley',
'last_name' => 'Sustaire',
'date' => '6/26/2019', // <== Want to rename the key from "date" to "date_db"
'amazing' => 'yes',
);
// Get the field value
$date_field = $fields['date'];
// Get the key position in the array (numeric)
$key_position = array_search( 'date', array_keys($fields) );
// Remove the original value
unset($fields['date']);
// Add the new value back in, with the new key, at the old position
$fields = array_merge(
array_slice( $fields, 0, $key_position, true ),
array( 'date_db' => $date_field ), // Notice the new key ends with "_db"
array_slice( $fields, $key_position, null, true )
);
/*
Input:
Array(
[first_name] => Radley
[last_name] => Sustaire
[date] => 6/26/2019
[amazing] => yes
)
Output:
Array(
[first_name] => Radley
[last_name] => Sustaire
[date_db] => 6/26/2019
[amazing] => yes
)
*/
//我们的数组
$fields=数组(
“名字”=>“雷德利”,
“姓氏”=>“Sustaire”,
“日期”=>“2019年6月26日”/“是”,
);
//获取字段值
$date_field=$fields['date'];
//获取数组中的键位置(数字)
$key_position=array_search('date',array_keys($fields));
//删除原始值
未设置($fields['date']);
//使用新键将新值添加回旧位置
$fields=array\u merge(
数组\u切片($fields,0,$key\u position,true),
数组('date\u db'=>$date\u字段),//注意新键以“\u db”结尾
数组\u切片($fields,$key\u位置,null,true)
);
/*
输入:
排列(
[名字]=>Radley
[姓氏]=>Sustaire
[日期]=>2019年6月26日
[惊人]=>是的
)
输出:
排列(
[名字]=>Radley
[姓氏]=>Sustaire
[日期]=>2019年6月26日
[惊人]=>是的
)
*/
经过
看看这个:我可以看到它在foreach内部工作,但是一旦超出它,它的值似乎仍然是旧的。我想我需要添加“&”。我会更改:
$keys[array\u search($oldKey,$keys)]=$newKey代码>收件人:$keys[array\u search($oldKey,array\u map('strval',$keys))]=$newKey代码>这里是我遇到的问题:我还能够使用您的函数w/array\u walk(递归)。谢谢谢谢你@EllisGL。我已经用你的评论更新了答案,以及一个新的单元测试来涵盖这个特定问题。只有在你没有重复值的情况下。那$item来自哪里?
<?php
/**
* Rename a key and preserve the key ordering.
*
* An E_USER_WARNING is thrown if there is an problem.
*
* @param array &$data The data.
* @param string $oldKey The old key.
* @param string $newKey The new key.
* @param bool $ignoreMissing Don't raise an error if the $oldKey does not exist.
* @param bool $replaceExisting Don't raise an error if the $newKey already exists.
*
* @return bool True if the rename was successful or False if the old key cannot be found or the new key already exists.
*/
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;
}
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', // Index 0
'car' => 'fast',
'none', // Index 1
];
$this->assertTrue(Arrays::renameKey($data, 'car', 2));
$this->assertEquals(
[
0 => 'nice',
2 => 'fast',
1 => 'none',
],
$data
);
}
function arrayReplaceKey($array, $oldKey, $newKey) {
$r = array();
foreach ($array as $k => $v) {
if ($k === $oldKey) $k = $newKey;
$r[$k] = $v;
}
return $r;
}
// Our array
$fields = array(
'first_name' => 'Radley',
'last_name' => 'Sustaire',
'date' => '6/26/2019', // <== Want to rename the key from "date" to "date_db"
'amazing' => 'yes',
);
// Get the field value
$date_field = $fields['date'];
// Get the key position in the array (numeric)
$key_position = array_search( 'date', array_keys($fields) );
// Remove the original value
unset($fields['date']);
// Add the new value back in, with the new key, at the old position
$fields = array_merge(
array_slice( $fields, 0, $key_position, true ),
array( 'date_db' => $date_field ), // Notice the new key ends with "_db"
array_slice( $fields, $key_position, null, true )
);
/*
Input:
Array(
[first_name] => Radley
[last_name] => Sustaire
[date] => 6/26/2019
[amazing] => yes
)
Output:
Array(
[first_name] => Radley
[last_name] => Sustaire
[date_db] => 6/26/2019
[amazing] => yes
)
*/
foreach($arr as &$m)
{
$m['first_name'] = $m['n'];
$m['last_name'] = $m['l'];
unset($m['l'], m['n']);
}
print_r($arr);